How do I define my own feedback messages in Wicket? For example: if I give an incorrect username, I want to get an error message like \"The user name in incorrect, try to login
you should set Feed back message to Session
message = "message";
Session.get().getFeedbackMessages().success(null, message);
You can use an anonymous IValidationError class and the messageSource.getMessage method to get a custom message from your property file:
error(new IValidationError() {
@Override
public Serializable getErrorMessage(IErrorMessageSource messageSource) {
//create a list of the arguments that you will use in your message string
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("invalidUsername", getInvalidUsernameInput());
//get the message string from the property file
return messageSource.getMessage("mysettings.invalid_username", vars);
}
});
Sample property file:
mysettings.invalid_username=The user name "${invalidUsername}" is incorrect.
@user1090145: I've used overloaded Component's error() method in Validator's class:
private void error(IValidatable<String> validatable, String errorKey) {
ValidationError error = new ValidationError();
error.addMessageKey(errorKey);
validatable.error(error);
}
and invoked it in validate() by
error(validatable, "your-form.field.text-id");
Properties your-form.field.text-id must be defined in YourPage.properties
Sources: Create custom validator in Wicket and Form validation messages
You can display your own error messages using error()
and warn()
and info()
. If you want to show errors dependent on validators or the required flag you can define a properties file with the same name as the class which contains a mapping of field -> message. For example:
Index.java
Form form = new Form("myform");
form.add(new TextField("name").setRequired(true));
form.add(new PasswordTextField("password").setRequired(true));
form.add(new TextField("phonenumber").setRequired(true));
Index.properties
Required=Provide a ${label} or else...
All required fields
myform.name.Required=You have to provide a name
The field name
in the form myform
when it is required.
password.Required=You have to provide a password
Any field with the name password
when it is required.
phonenumber.Required=A telephone number is obligatory.
Any field with the name phonenumber
when it is required.
This shows a variety of ways of setting a feedback message for specific components.
You can also put the properties files next to the following component level (in order of importance, top highest):
Hope that helps