Reputation: 25
How does the Model work?
I have a Registry Class like this:
public class RegisterPanel extends Panel{
//empty user
public User user = new User();
protected ServiceClient client = ((WicketApplication) (WicketApplication.get())).getClient();
@SuppressWarnings({ "rawtypes" })
public RegisterPanel(String id) {
super(id);
//creates form with an empty user
Form form = new RegisterForm("registerForm", user);
add(form);
}
@SuppressWarnings({ "rawtypes" })
class RegisterForm extends Form {
private String userId = "";
private String email = "";
private String password1 = "";
private String password2 = "";
private FormComponent formEmail;
private FormComponent formPassword1;
private FormComponent formPassword2;
@SuppressWarnings("unchecked")
public RegisterForm(String id, User user) {
super(id);
add(new TextField("userId", new PropertyModel(this, "userId")).setRequired(true));
formEmail = new TextField("email", new PropertyModel(this, "email")).setRequired(true);
formPassword1 = new PasswordTextField("password1", new PropertyModel(this, "password1")).setRequired(true);
formPassword2 = new PasswordTextField("password2", new PropertyModel(this, "password2")).setRequired(true);
add(formEmail);
add(formPassword1);
add(formPassword2);
}
@Override
public void onSubmit() {
Result result = client.register(email, userId, password1);
if(result.getStatus()) {
user.setEail(email);
user.setUserId(userId);
user.setPassword(password1);
client.postUser(user);
}
}
}
}
But how do I work with models? Now I just bound PropertyModels to my TextFields. I thought I can bind a model to my empty user and on the submit method I work on my model instead on my plain user. How does it work? Whats the advantage of working on models?
Upvotes: 0
Views: 490
Reputation: 5681
Working with models has several advantages:
public class RegisterPanel extends Panel{
protected ServiceClient client = ...
public RegisterPanel(String id) {
super(id);
//creates form with an empty user
Form<Void> form = new RegisterForm<Void>("registerForm", new Model(new User()));
add(form);
}
class RegisterForm extends Form<Void> {
public RegisterForm(String id, IModel<User> user) {
super(id);
add(new TextField("userId", new PropertyModel(user, "userId")).setRequired(true));
add(new TextField("email", new PropertyModel(user, "email")).setRequired(true);
add(new PasswordTextField("password", new PropertyModel(user, "password")).setRequired(true);
add(new PasswordTextField("password2", new Model("").setRequired(true);
}
@Override
public void onSubmit() {
try {
client.registerAndPost(email, userId, password1);
} catch (ServiceException ex) {
...
}
}
}
Note:
Upvotes: 1