Java Play! Framework - Unable to populate form with existing value - playframework-2.3

I am using Java Play framework 2.3.6 .I can't able to populate the form with existing value.
Given below the code snippets.
Application.java
public class Application extends Controller{
static Form<Roles> rolesForm=Form.form(Roles.class);
public static Result getRoleById(Long id){
Roles r = RolesDao.getRoleById(id);
//rolesForm.fill(RolesDao.getRoleById(id));
rolesForm.fill(r);
return ok(updateRole.render(rolesForm));
}}
updateRole.scala
#(roleForm : Form[models.Roles])
#import helper._
#main("Update Role Details"){
#form(routes.Application.updateRole(Long Id)){
#inputText(roleForm("role_short_description"))
#inputText(roleForm("role_long_description"))
#inputRadioGroup(roleForm("active_yn"))
<br>
<input type="submit" value="Update">
}
}
Roles.java
public class Roles extends Model{
#Id
#SequenceGenerator(schema=Roles.SCHEMA,name="gen", sequenceName="role_id_seq",allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="gen")
public Long role_id;
#Required
public String role_short_description=null;
#Required
public String role_long_description=null;
public String active_yn=null;
RolesDAO.java
public class RolesDao {
public static Finder<Long,Roles> find = new Finder<Long, Roles>(
Long.class, Roles.class
);
public static Roles getRoleById(Long id) {
return find.where().eq("role_id", id).findUnique();
}}

Try this,
public class Application extends Controller{
public static Result getRoleById(Long id){
Roles role = RolesDao.getRoleById(id);
Form<Roles> rolesForm = Form.form(Roles.class).fill(role);
return ok(updateRole.render(rolesForm));
}
}
Always keep the form inside Action method rather than keeping it globally.

Related

Blaze Persistence EntityView inheritance mapping

I'm currently using Quarkus combined with Blaze Persistence for my microservice. I have the following entity model:
#Entity
public class Content extends BaseEntity {
private boolean deleted;
private boolean published;
}
#Entity
public class WebContent extends Content {
private String webpage;
}
I've mapped the entities to the following EntityViews:
#EntityView(Content.class)
#EntityViewInheritance
#CreatableEntityView
#UpdatableEntityView
public interface ContentUpdateView {
#IdMapping
Long getId();
boolean isPublished();
void setPublished(boolean published);
}
#EntityView(WebContent.class)
#CreatableEntityView
#UpdatableEntityView
public interface WebContentUpdateView extends ContentUpdateView {
String getWebpage();
void setWebpage(String webpage);
}
I have the following method in my ContentsResource:
#POST
public ContentUpdateView save(ContentUpdateView content) {
return contentsService.save(content);
}
When I invoke the post operation I only get the base ContentUpdateView and not the WebContentUpdateView. Is there any configuration to do? (with Jackson I use #JsonTypeInfo and #JsonSubType annotation on the entities to accomplish this).
Thanks
euks
I got it working using Jackson annotation. Here's the base class:
#EntityView(Content.class)
#EntityViewInheritance
#JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type")
#JsonSubTypes({
#JsonSubTypes.Type(value = DescriptiveContentView.class, name = "descriptive"),
#JsonSubTypes.Type(value = MediaContentView.class, name = "media"),
#JsonSubTypes.Type(value = WebContentView.class, name = "web")
})
#JsonTypeName("content")
public abstract class ContentView {
#IdMapping
public abstract Long getId();
public abstract boolean isPublished();
}
And here's a subclass:
#EntityView(DescriptiveContent.class)
#JsonTypeName("descriptive")
public abstract class DescriptiveContentView extends ContentView {
public abstract Set<LocalizedParagraphView> getLocalizedParagraphs();
}
I'm using abstract classes for other purposes, but it also works with interfaces.

How to deserialize json to an abstract class in spring-boot

In my Application i have something like this.
public class Question{}
public class MCQ extends Question{}
public class TrueAndFalse Question{}
public class Match Question{}
and in my RestController i have a service that adds question.
#RequestMapping(value = "/game/question/add", method = RequestMethod.POST)
public Question addQuuestion(#RequestParam("gameId") long id, #RequestBody Question question)
But i get an error when i try to call this service as i send json file with different structures one for MCQ, TrueAndFalse and Match.
so is it possible to deserialize the received json to Question abstract class.
And thanks in advance.
You can create a custom deserializer which will create Question instances based on json payload properties.
For example if the Question class looks like this:
public class Question {
private final String name;
#JsonCreator
Question(#JsonProperty("name") String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And sub-class TrueAndFalse:
public class TrueAndFalse extends Question {
private final String description;
#JsonCreator
TrueAndFalse(#JsonProperty("name") String name,
#JsonProperty("description") String description) {
super(name);
this.description = description;
}
public String getDescription() {
return description;
}
}
Then you can create a deserializer, which will create an instance of TrueAndFale sub-class by checking if it has description property:
public class QuestionDeserializer extends JsonDeserializer<Question> {
#Override
public Question deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
ObjectCodec codec = p.getCodec();
JsonNode tree = codec.readTree(p);
if (tree.has("description")) {
return codec.treeToValue(tree, TrueAndFalse.class);
}
// Other types...
throw new UnsupportedOperationException("Cannot deserialize to a known type");
}
}
And afterwards, make sure to register it on the object mapper:
#Configuration
public class ObjectMapperConfiguration {
#Bean
public ObjectMapper objectMapper() {
SimpleModule module = new SimpleModule();
module.addDeserializer(Question.class, new QuestionDeserializer());
return new ObjectMapper().registerModules(module);
}
}

MVC 5 View dynamically add or delete list of model

I have a model
public class DeModel
{
public string id{get;set;}
public string Name{get;set;}
public List<AdressesModel>{get;set;}
}
public class AdressesModel
{
public string id{get;set;}
public string line1{get;set;}
public string line2{get;set;}
public string hometown{get;set;}
public string city{get;set;}
public string country{get;set;}
}
In my view, user should be able to add or delete addresses and I should be able to get the final list on the post back.
Js is one way , but it is too complicated , I have to keep track of the indexes and I need to change alot when the model changes.
I see that editorfortemplates with ajax call is an option but couldn't figure out how to do that .
How can I do this other than JS ?

RestyGWT Polymorphic Encode/Decode issues when using an interface instead of an abstract class

According to RestyGWT documentation one must use an abstract super class for this to work, for instance, given:
#JsonSubTypes(#Type(value=PersonImpl.class, name="PersonImpl"))
#JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property="#class")
public abstract class Person{
public abstract String getName();
public abstract void setName(String name);
}
#JsonTypeName("PersonImpl")
public class PersonImpl extends Person{
private String name;
#Override
public final String getName() {
return name;
}
#Override
public final void setName(String name) {
this.name = name;
}
}
If I use the defined encoder/decoder this would work:
Person personInstance = new PersonImpl();
personInstance.setName("TestName");
PersonCodec codec = GWT.create(PersonCodec.class);
JSONValue json = codec.encode(personInstance);
Im trying to do something quite similar but with a small difference, that is, instead of Person being an abstract class I want it to be an Interface:
#JsonSubTypes(#Type(value=PersonImpl.class, name="PersonImpl"))
#JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property="#class")
public interface Person{
public String getName();
public void setName(String name);
}
For some reason this doesn't seem to work, as soon as I do that I start getting Errors when the JsonEncoderDecoder is generated. Has someone been able to achieve this?
Thanks!
Why not define your interface and make your abstract class implement it?

GWT Autobean without setter method

I am using Autobean framework to encode/decode JSON in my GWT application. It works in cases with the interfaces having getters and setters. But is there any way to do it some other way to do this without specifying a setThisCollectionProperty instead using an addToThisCollectionProperty method?
For example, I have an interface IPerson like this:
public interface IPerson {
public String getName();
public void setName(String name);
public int getAge();
public void setAge(int age);
public List<String> getIds();
public void addId(String id);
}
BeanFactory is like this:
public interface BeanFactory extends AutoBeanFactory {
public AutoBean<IPerson> person();
public AutoBean<IPerson> person(IPerson person);
}
and in Person class which implements IPerson,
public class Person implements IPerson {
private String name;
private List<String> ids;
...
public List<String> getIds() {
return ids;
}
public void addId(String id) {
...
ids.add(id);
}
}
It works if the addId(String id) is replaced with setIds(List<String> ids).
Otherwise the following error is shown:
The com.mycompany.jsonsample.beans.IPerson parameterization is not simple, but the person method does not provide a delegate
Is it possible to encode/decode without a set method?
AutoBean manages all getters and setters, and only getters and setters. For any other method, you have to use a category.
Using a category, you could thus implement addId(…) as getIds().add(…), or possibly directly call addIds on the underlying object if the AutoBean is a wrapper.