Fill form with values from DB in Wicket - java

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.

Related

Wicket - Appending values to json schema

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.

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.

how to use php in gwt

it's as it says on the title
First of all, I would like to apologize if this is a dumb question =[
so basically i'm trying to send email through gwt. I have no idea how gwt mail work so instead I tried to use php way (which is more familiar to me) but I have no idea how to get this working.
So.. in my war folder I have my index.html and email.php that I've created. In my index.html, I have a form that calls my email.php.
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "did you make sure to fill everything?";
return false;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'myemail#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email\n\n Message:\n$message";
$headers = "From: noreply#somedomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
above is my php code that I am currently using. However not only eclipse does not recognize php but also when I press my button, it only prints out this code and not running it.
Does this happen to anyone and can anyone please help me?
Thank you =]
What you can do:
Recreate the email form in GWT with FormPanel, or
create your own POST-Request in GWT with RequestBuilder
In both cases: the 'echo' statements that your PHP form returns will not be appended to the HTML page but returned to you as a String. You will have to decide what to do (tell the user? take other action) in your GWT code.
Recreate as form panel:
// create the textboxes of the form with their proper form names
TextBox tbName = new TextBox();
tbName.setName( "name" );
TextBox tbEmail = new TextBox();
tbEmail.setName( "email" );
TextBox tbMessage = new TextBox();
tbMessage.setName( "message" );
// create the form panel
final FormPanel emailFormPanel = new FormPanel();
// TODO: add the form panel to some kind of parent widget / ui object
emailFormPanel.setAction( "/contextRoot/path/to/email.php" );
emailFormPanel.setMethod( "POST" );
// add the textboxes to the form panel
emailFormPanel.add( tbName );
emailFormPanel.add( tbEmail );
emailFormPanel.add( tbMessage );
// create the form submit button
Button btnSubmit = new Button( "Submit", new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
emailFormPanel.submit();
}
} );
// create the formpanel handler for a successful submit
// any error message ("did you forget to ...") will be returned here
emailFormPanel.addSubmitCompleteHandler( new SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
String errorString = event.getResults();
// TODO: decide what to do with a potential non-empty string
}
} );
Create your own POST-Request with RequestBuilder:
// create the textboxes of the form with their proper form names
final TextBox tbName = new TextBox();
final TextBox tbEmail = new TextBox();
final TextBox tbMessage = new TextBox();
// create the form submit button
Button btnSubmit = new Button( "Submit", new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
submitEmailFormRequestBuilder( tbName, tbEmail, tbMessage );
}
} );
// TODO: add textboxes and Submit-Button to the DOM-tree
submit the textbox values:
protected void submitEmailFormRequestBuilder(TextBox name, TextBox email, TextBox message) {
// create the request content in a way that the php script can read it:
// for every textbox the php textbox-name = user-value
StringBuilder requestData = new StringBuilder();
requestData.append( "name=" + name.getValue() );
requestData.append( "&email=" + email.getValue() );
requestData.append( "&message=" + message.getValue() );
// create the REST request callback
RequestCallback callback = new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
String errorMessage = response.getText();
// TODO: handle potential error-message
}
#Override
public void onError(Request request, Throwable exception) {
// TODO: handle timeouts and other sending failures like cross-domain posting
}
};
// create the REST request as POST request
RequestBuilder build = new RequestBuilder( RequestBuilder.POST, "/contextRoot/email.php" );
try {
build.sendRequest( requestData.toString(), callback );
}
catch (RequestException e) {
// handle exception
}
}
Otherwise, if index.html is not your GWT starting page where the .nocache.js module is called, then you could include it in your GWT code with an IFrame.

GWT CellTable with UIBinder

I am trying to display a very simple cellTable on click of a button in my page.
However, the celltable is not getting rendered.
Giving below code snippets for more understanding:
preview.ui.xml file
<g:HTMLPanel>
<div class="{bundle.css.roundedBorder}">
<table style='width:100%;'>
<tr>
<td>
<c:CellTable pageSize='15' ui:field='cellTable' width="100%">
</c:CellTable>
</td>
</tr>
</table>
</div>
</g:HTMLPanel>
Correspoding Java Class:
public class Preview extends Composite {
.
.
. // other generic GWT code to bind UIBinder XML with this class
.
.
.
#UiField
CellTable<Contact> cellTable;
#UiHandler("button")
void handleClickOnSearchButton(ClickEvent e) {
cellTable = configureCellTable();
}
private CellTable<Contact> configureCellTable() {
// The list of data to display.
List<Contact> CONTACTS = Arrays.asList(new Contact("John", "123 Fourth Road"), new Contact("Mary", "222 Lancer Lane"), new Contact("Zander", "94 Road Street"));
// Create a CellTable.
CellTable<Contact> table = new CellTable<Contact>();
// Create name column.
TextColumn<Contact> nameColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact contact) {
return contact.name;
}
};
// Create address column.
TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact contact) {
return contact.address;
}
};
// Add the columns.
table.addColumn(nameColumn, "Name");
table.addColumn(addressColumn, "Address");
// Create a data provider.
ListDataProvider<Contact> dataProvider = new ListDataProvider<Contact>();
// Connect the table to the data provider.
dataProvider.addDataDisplay(table);
// Add the data to the data provider, which automatically pushes it to the widget.
List<Contact> list = dataProvider.getList();
for (Contact contact : CONTACTS) {
list.add(contact);
}
return table;
}
private static class Contact {
private final String address;
private final String name;
public Contact(String name, String address) {
this.name = name;
this.address = address;
} } }
Please guide!
Thanks,
Akshay
You have two different cellTable objects. One is created by UiBinder and one is created in your configureCellTable Method.
Try to add a SimplePanel in your UiBinder file instead of the table:
<td>
<g:SimplePanel ui:field="simplePanel"/>
</td>
And in your Java code you add the table on it:
#UiField
SimplePanel simplePanel;
...
private CellTable<Contact> configureCellTable() {
...
simplePanel.add(table);
}

ExtGWT StoreFilterField input doesn't react

I'm trying to build grid with build in column filtering (using sencha gxt), here is my code:
public Grid<Stock> createGrid() {
// Columns definition
ColumnConfig<Stock, String> nameCol = new ColumnConfig<Stock, String>(props.name(), 100, "Company");
// Column model definition and creation
List<ColumnConfig<Stock, ?>> cl = new ArrayList<ColumnConfig<Stock, ?>>();
cl.add(nameCol);
ColumnModel<Stock> cm = new ColumnModel<Stock>(cl);
// Data populating
ListStore<Stock> store = new ListStore<Stock>(props.key());
store.addAll(TestData.getStocks());
// Grid creation with data
final Grid<Stock> grid = new Grid<Stock>(store, cm);
grid.getView().setAutoExpandColumn(nameCol);
grid.setBorders(false);
grid.getView().setStripeRows(true);
grid.getView().setColumnLines(true);
// Filters definition
StoreFilterField<Stock> filter = new StoreFilterField<Stock>() {
#Override
protected boolean doSelect(Store<Stock> store, Stock parent, Stock item, String filter) {
// Window.alert(String.valueOf("a"));
String name = item.getName();
name = name.toLowerCase();
if (name.startsWith(filter.toLowerCase())) {
return true;
}
return false;
}
};
filter.bind(store);
cm.addHeaderGroup(0, 0, new HeaderGroupConfig(filter, 1, 1));
filter.focus();
return grid;
}
My problem is: after I run this code, I cannot write anything to filter input, I'm using test data and classes (Stock.java and StockProperties.java) from this example: http://sencha.com/examples-dev/#ExamplePlace:filtergrid
I try to put allert in doSelect method to check if this function was called, but it wasn't.
Any idea will be welcome. Thanks.
I was able to make your code work. I observed that there were compiler errors in the code for StoreFilterField class. Here is the code that filters the grid based on the values in the first column, that is, name field in the Stock model.
StoreFilterField<Stock> filter1 = new StoreFilterField<Stock>() {
#Override
protected boolean doSelect(Store<Stock> store, Stock parent, Stock record, String property, String filter) {
String name = record.get("name");
name = name.toLowerCase();
if (name.startsWith(filter.toLowerCase())) {
return true;
}
return false;
}
};
filter1.bind(store);
Btw, I tested this with GXT 2.2.5 and GWT 2.4.
Thanks,
Ganesh
I solve this problem according to this paper http://www.sencha.com/forum/archive/index.php/ … but I replace disableTextSelection(false) with setAllowTextSelection(true);

Categories