Wicket - Appending values to json schema - java

NewForm.java
public class NewForm extends WebPage {
private Bean bean;
private DropDownClass dropdown;
private String selected = "choice";
void init()
{
bean = new Bean();
dropdown=new DropDownClass("test");
}
public NewForm(final PageParameters page) {
init();
final TextField<String> textname = new TextField<String>("name",Model.of(""));
textname.setRequired(true);
final DropDownChoice<String> dropname = new DropDownChoice<String>("type", new PropertyModel<String>(this, "selected"),
dropdown.getlist());
Form<?> form = new Form<Void>("Form") {
#Override
public void onSubmit() {
final String name = (String) textname.getModelObject();
final String dropdown = (String)dropname.getModelObject();
bean.add(name,dropdown);
final String schema = bean.getJsonSchema().toString();
page.add("schema", schema);
setResponsePage(new NewForm(page));
}
};
Label schemalabel = new Label("schema", page.get("schema"));
add(form);
form.add(textname);
form.add(dropname);
form.add(schemalabel);
}
}
Bean.java
public class Bean
{
private JSONObject jsonSchema;
public JSONObject getJsonSchema() {
return jsonSchema;
}
public void setJsonSchema(JSONObject jsonSchema) {
this.jsonSchema = jsonSchema;
}
public Bean() {
jsonSchema = new JSONObject();
}
public void add(String key,String value)
{
jsonSchema.put(key, value); // I am able to append values each time using "put" or "append" in JSF but not in WICKET.How can I append values in Wicket?
//or jsonSchema.append(key, value); //adding values only once and not appending each time,I enter the values in TextField and DropDown
}
}
In CreateForm.java - I have a Textfield and DropDown. When I enter the values in TextField and DropDown..I am able to convert the values entered in TextField and DropDown as JSON schema from method add(String key,String value) in AttributeInfo.java and display the schema as - {"name":"abc"} //where name is value entered in TextField and abc is from DropDown.
I am able to display the schema only once onSubmit But I need to append the values to schema each time,I enter in TextField and DropDown onSubmit and display in the samepage.
How can I achieve this in Wicket?
I am just a beginner.Any Help would be appreciated.Thankyou in advance.

Related

Is there a way to get an input value in Java - elemental2?

Is there a way to read an input value as in JavaScript using java - elemental2?
My entire code looks like this:
public void onModuleLoad() {
document.body.style.margin = MarginUnionType.of("0");
document.body.appendChild(navigation());
document.body.appendChild(mainSection());
}
// *********************** //
// Elemental methods
public static HTMLElement mainSection() {
// create list
HTMLElement ul = (HTMLElement) document.createElement("ul");
ul.style.listStyle = "none";
HTMLElement li = (HTMLElement) document.createElement("li");
li.textContent = "Tasks";
ul.appendChild(li);
return ul;
}
public static HTMLElement navigation() {
// create button
HTMLButtonElement button = (HTMLButtonElement) document.createElement("button");
button.textContent = "Add Task";
button.addEventListener("click", evt -> onAddTask());
// create main nav
HTMLElement mainNav = (HTMLElement) document.createElement("nav");
mainNav.className = "main-nav";
mainNav.appendChild(addInput());
mainNav.appendChild(button);
return mainNav;
}
public static HTMLInputElement addInput() {
// create input
HTMLInputElement input = (HTMLInputElement) document.createElement("input");
input.placeholder = "Enter your name here";
input.id = "tasks-input";
return input;
};
public static void onAddTask() {
alert(document.getElementById("tasks-input").getAttribute("value"));
}
}
Basically when I click on the button I want to print whatever I typed into the input.
Thanks!
Generally with elemental2 you can use a DOM API object's property directly. So according to:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
you can do the following in java with elemental2:
HTMLInputElement input;
input.value = "foo";
String value = input.value;

Fill form with values from DB in Wicket

I have a form with the following logic:
TextField name = new TextField<>("name", Model.of(""));
TextField surname = new TextField<>("surname", Model.of(""));
TextField mobile = new TextField<>("mobile", Model.of(""));
TextField phone = new TextField<>("phone", Model.of(""));
HiddenField id = new HiddenField<>("id", Model.of(""));
EmailTextField email = new EmailTextField("email", Model.of(""));
Form form = new Form("formContact") {
#Override
protected void onSubmit() {
super.onSubmit();
Contact contact = new Contact();
contact.setName(name.getValue());
contact.setEmail(email.getValue());
contact.setSurname(surname.getValue());
contact.setMobile(mobile.getValue());
contact.setPhone(phone.getValue());
service.save(contact);
}
};
form.add(id);
form.add(email.setRequired(false));
form.add(name.setRequired(true));
form.add(surname.setRequired(true));
form.add(mobile.setRequired(true));
form.add(phone.setRequired(false));
add(form);
I use that code when a client wants to insert a new Contact, and it works.
What I need now is to handle the update of an existing Contact, so I just need to fill an existing form with values from a known Contact instance:
Contact contact = service.get(1);
How can I do that?
Thanks
I would use CompoundPropertyModel for form so it will update when model is changing and also don't need set data to fields. Send model when you creating page or model, you can send contract instance(even empty one). Let's say your class name is MyPanel, then constructor
MyPanel(String id, IModel<Contract> model) {
super(id, model);
}
Now when you are creating form you can use CompoundPropertyModel benefits(in Contract class should be fields name, surname, mobile,etc with public getters and setters)
#Override
protected void onInitialize() {
super.onInitialize();
Form<Contract> form = new Form("formContact", new CompoundPropertyModel(getModel()){
#Override
protected void onSubmit() {
super.onSubmit();
service.save(getModelObject());
}
});
add(form);
form.add(new TextField<>("name").setRequired(true));
form.add(new TextField<>("surname").setRequired(true));
form.add(new TextField<>("mobile").setRequired(true));
form.add(new TextField<>("phone").setRequired(false));
form.add(new HiddenField<>("id"));
form.add(new EmailTextField("email").setRequired(false));
Let's update contract by button clicking
form.add(new AjaxLink<Void>("updateContract"){
#Override
public void onClick(AjaxRequestTarget target) {
form.setModelObject(service.get(1));
target.add(form);
}
});
You should use the existing contact's data in the models of the form components.
E.g. TextField name = new TextField<>("name", new PropertyModel(contact, "name"));
Also see CompoundPropertyModel.

vaadin BeanFieldGroup binding issue with combobox

I'm not sure if I understand correctly BeanFieldGroup but I hope it should bind values from fields(UI components) to my custom beans (eg POJOs).
Here I have my POJO.
public class JobConfigDTO {
#Max(50)
private String format;
#Max(50)
private String template;
#Max(50)
private String channel;
}
With this code I'm attempting to bind my POJO to checkboxes.
private void test(){
JobConfigDTO jobConfigDTO = new JobConfigDTO();
ComboBox comboChannel = createEditFormCombobox("Channel", "CHANNEL");
ComboBox comboFormat = createEditFormCombobox("Format", "FORMAT");
ComboBox comboTemplate = createEditFormCombobox("Template", "TEMPLATE");
BeanFieldGroup<JobConfigDTO> binder = new BeanFieldGroup<>(JobConfigDTO.class);
binder.setItemDataSource(jobConfigDTO);
binder.setBuffered(false);
binder.bind(comboChannel, "channel");
binder.bind(comboChannel, "channel");
binder.bind(comboFormat, "format");
binder.bind(comboTemplate, "template");
Button btnSave = new Button("Add");
btnSave.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(Button.ClickEvent event) {
try {
log.debug("jobconfigdto {}", jobConfigDTO);
binder.setBuffered(true);
log.debug("jobconfigdto {}", jobConfigDTO);
binder.commit();
binder.setBuffered(false);
} catch (FieldGroup.CommitException e) {
log.error("Unable to save job config", e);
}
}
});
}
When I set values for comboboxes in form and click add button pojo JobConfigDTO is not filled.
Am I missing something or BeanFieldGroup has another usage? I would like to bind values from checkboxes to my pojo class and validate them at the end.

Retrieve TextField value from the ListView

I have ListView.Where iam showing the some records.The ListView contain Lable and TextField.I entered some data in the textField(which is in ListView).On Submit() method,i am trying to retrieve the entered textfield value.But i am not getting the value which i entered in textbox.Please let me know how to get the entered value from textfield?Below is my code.
public List<StockCountDetail> getItemEntryDetails() {
List<StockCountDetail> myStockCountDetailList = new ArrayList<StockCountDetail>();
List<StockKeepingUnit> mySkuList = MpoBeanFactory.getBean(StockKeepingUnitDAO.class).getByStockLocation(stockLocationModel.getObject());
myStockCountDetailList.clear();
for (StockKeepingUnit mySku : mySkuList) {
StockCountDetail stockCountDetail = new StockCountDetail();
stockCountDetail.setProduct(mySku.getProduct());
myStockCountDetailList.add(stockCountDetail);
}
return myStockCountDetailList;
}
myStockCountDetailList = new ListView<StockCountDetail>("itemList", new PropertyModel<List<StockCountDetail>>(
StockCountEditPage.this, "itemEntryDetails")) {
#Override
protected void populateItem(ListItem<StockCountDetail> aItem) {
aItem.add(new AttributeAppender("class", true, new Model<String>(aItem.getIndex() % 2 == 0 ? "even" : "odd"), " "));
aItem.add(new Label("product", aItem.getModelObject().getProduct().getCode()));
aItem.add(new Label("description", aItem.getModelObject().getProduct().getDescription()));
aItem.add(new CheckBox("skipFlag", new PropertyModel<Boolean>(aItem.getModel(), "skipFlag")));
aItem.add(new TextField<Integer>("count", new PropertyModel<Integer>(aItem.getModel(), "count")));
}
};
myStockCountDetailList.setReuseItems(true);
form.add(myStockCountDetailList);
setOutputMarkupId(true);
AjaxFallbackButton mySave = new AjaxFallbackButton("save", form) {
#Override
protected void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) {
saveStockCount();
aTarget.addComponent(feedbackPanel);
}
};
form.add(mySave);
private void saveStockCount() {
boolean recordAdded = false;
for (StockCountDetail myStockCount : myStockCountDetailList.getModelObject()) {
if (!myStockCount.isSkipFlag()) {
myStockTransaction.setQuantity(new BigDecimal(myStockCount.getCount()));
}
here i am not getting the value using myStockCount.getCount() which is the entered value of textbox in listview.let me know how to get value of textbox?
Your ListView uses a PropertyModel that gets its value from calling getItemEntryDetails().
It you call myStockCountDetailList.getModelObject() then the resulting object will come from this.getItemEntryDetails() which will return a new List with new StockCountDetails.
In order to retain the value, you could store the list in a field.

Tapestry generates input tags in pair

I want to generate HTML5 valid document, but I have a problem with forms in my Tapestry app. I am using tapestry textfields like below:
<t:textfield t:id="specId" value="val" />
Tapestry generates html input element:
<input id="specId" name="specId" type="text"></input>
But element input is not valid in pair (with end tag </input>) and html validator yells: "Error: Stray end tag input.".
Is any way how to generate input tags in single form like
<input .../> ?
You can override MarkupWriterFactory service with its own MarkupModel that will abbreviate html5 void elements instead of rendering end tag.
public class Html5MarkupModel extends AbstractMarkupModel {
private static final Set<String> VOID_ELEMENTS = new HashSet<String>(Arrays.asList(
"area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"
));
public Html5MarkupModel(boolean useApostropheForAttributes) {
super(useApostropheForAttributes);
}
public EndTagStyle getEndTagStyle(String element) {
return VOID_ELEMENTS.contains(element) ? EndTagStyle.ABBREVIATE : EndTagStyle.REQUIRE;
}
public boolean isXML() {
return false;
}
}
public class Html5MarkupWriterFactory implements MarkupWriterFactory {
private final PageContentTypeAnalyzer analyzer;
private final RequestPageCache cache;
private final MarkupModel htmlModel = new Html5MarkupModel(false);
private final MarkupModel htmlPartialModel = new Html5MarkupModel(true);
private final MarkupModel xmlModel = new XMLMarkupModel();
private final MarkupModel xmlPartialModel = new XMLMarkupModel(true);
public Html5MarkupWriterFactory(PageContentTypeAnalyzer analyzer, RequestPageCache cache) {
this.analyzer = analyzer;
this.cache = cache;
}
public MarkupWriter newMarkupWriter(ContentType contentType) {
return newMarkupWriter(contentType, false);
}
public MarkupWriter newPartialMarkupWriter(ContentType contentType) {
return newMarkupWriter(contentType, true);
}
public MarkupWriter newMarkupWriter(String pageName) {
return newMarkupWriter(analyzer.findContentType(cache.get(pageName)));
}
private MarkupWriter newMarkupWriter(ContentType contentType, boolean partial) {
boolean isHTML = contentType.getMimeType().equalsIgnoreCase("text/html");
MarkupModel model = partial
? (isHTML ? htmlPartialModel : xmlPartialModel)
: (isHTML ? htmlModel : xmlModel);
// The charset parameter sets the encoding attribute of the XML declaration, if
// not null and if using the XML model.
return new MarkupWriterImpl(model, contentType.getCharset());
}
}
And service override contribution:
#Contribute(ServiceOverride.class)
public void contributeServiceOverrides(MappedConfiguration<Class, Object> configuration,
ObjectLocator objectLocator) {
// use proxy instead of real service instance
// to prevent recursion on initialization cycle
configuration.add(MarkupWriterFactory.class,
objectLocator.proxy(MarkupWriterFactory.class, Html5MarkupWriterFactory.class));
}

Categories