I have the following Model class:
public class BlocchettiScratchCards implements Serializable {
...
private boolean flagNuovaGestione;
public boolean isFlagNuovaGestione() {
return flagNuovaGestione;
}
public void setFlagNuovaGestione(boolean flagNuovaGestione) {
this.flagNuovaGestione = flagNuovaGestione;
}
}
and the Bean class:
public class BlocchettiScratchCardsBean implements Serializable {
...
private boolean flagNuovaGestione;
public boolean isFlagNuovaGestione() {
return flagNuovaGestione;
}
public void setFlagNuovaGestione(boolean flagNuovaGestione) {
this.flagNuovaGestione = flagNuovaGestione;
}
}
in the JSP we have a <form:form> tag with the following:
<form:checkbox path="flagNuovaGestione"/>
The controller class initialize the property as follows:
BlocchettiScratchCardsBean elencoCards = new BlocchettiScratchCardsBean();
elencoCards.setFlagNuovaGestione(true);
but when the page is loaded, the checkbox is not checked by default as I expect.
Inspecting HTML of page, I see the following:
<input id="flagNuovaGestione1" name="flagNuovaGestione" type="checkbox" value="true">
<input type="hidden" name="_flagNuovaGestione" value="on">
but the checked property is not set.
Why do I have this behaviour and how could I solve this issue?
I've found the solution on my own.
The problem was into the Controller class, in particular the instruction that adds the formBean into the jsp view was executed before the setting of the flagNuovaGestione boolean variable.
This was the old / not working code:
BlocchettiScratchCardsBean elencoCards = new BlocchettiScratchCardsBean();
view.addObject("formBean", elencoCards);
elencoCards.setFlagNuovaGestione(true);
and the following is the right one:
BlocchettiScratchCardsBean elencoCards = new BlocchettiScratchCardsBean();
elencoCards.setFlagNuovaGestione(true);
view.addObject("formBean", elencoCards);
Related
Textbox should accept only numbers, I would like to use anyother Handlers other than ChangedHandler/ Changehandler/ KeyPressHandler
My Validation class,
public class UnderLyingIDChangeHandler implements ChangedHandler {
private final CreditRiskView creditRiskView;
public UnderLyingIDChangeHandler(CreditRiskView creditRiskView) {
this.creditRiskView = creditRiskView;
}
#Override
public void onChanged(ChangedEvent event) {
String value= (String) event.getItem().getValue();
if(!value.matches("[0-9]*")){
creditRiskView.invalidUnderlyingID();
}
}
This is the main class where I need to show the validation
public class CreditRiskView{
private TextItem underlyingIDField;
public void addunderlyingIDInputChangeHadler(ChangedHandler changedHandler) {
//logic is that this method will invoked in the UnderLyingIDChangeHandler class
underlyingIDField.addChangedHandler(changedHandler);
}
public void invalidUnderlyingID(){
// I don't know how to set an error message as underlyingIDField.clearValue()
method is not doing well.
}
}
If the textbox is a TextItem in a DynamicForm it works like this:
IsIntegerValidator isIntegerValidator = new IsIntegerValidator();
isIntegerValidator.setErrorMessage("error message");
textItem.setValidators(isIntegerValidator);
And to show the errors like that when you call the form.validate() you need to set the setShowInlineErrors(true) in the form.
What about limiting characters that can be entered by the user?
Please see this sample:
http://www.smartclient.com/smartgwt/showcase/#form_keypress_filter
I have the following flows for an application when a submit button is clicked:
1)The viewActivity method is called from ActivityController.java
ActivityController.java
#ActionMapping(params = "ActivityController=showActivity")
public void viewActivity(#RequestParam Integer index, ActionResponse response, Model model, #ModelAttribute Header header,
....
model.addAttribute("recoveryForm", new RecoveryForm(detailsResult.getDetails()));
response.setRenderParameter("ServiceController", "showService");
}
2) Then showRecovery method is called from serviceConroller as show below:
ServiceController.JAVA
#RenderMapping(params = "ServiceController=showService")
public String showRecovery(#ModelAttribute recoveryForm form, #ModelAttribute header header) {
.....
return service;
}
Then my service.jsp is displayed
Basically i have to display the value of a variable which is detailName found in DetailsResult.getDetails() object which i have added to my model as
it can be seen in viewActivity method found in ActivityController.java showed ealier.
I know when we add model.addAttribute it should be able to be displayed on this jsp using the following tag :
<form:input path="..." />
But in this case it is added to as a constructor argument as shown below:
model.addAttribute("recoveryForm", new RecoveryForm(detailsResult.getDetails()));
I have the following variable on my RecoveryForm:
public class RecoveryForm implements Serializable {
private CDetails Cdlaim;
private Action addAction;
private String addRemark;
private String remarks;
public RecoveryForm(CDetails Cdlaim) {
...
}
...
}
However i don't have the detailsResult in my RecoveryForm.
Any idea how i can get a value which is in DetailsResult.getDetails() in my service.jsp?
I believe you are looking at this the wrong way. The value of DetailsResult.getDetails() is obviously stored in RecoveryForm as a property somehow. So, I'm going to assume your RecoveryForm looks something like:
public class RecoveryForm {
private String details;
public RecoveryForm(String details) {
this.details = details;
}
public String getDetails() {
return details;
}
}
When you bind to a form in your jsp, you need to nest your <form:input ...> tag in a <form:form ...> tag:
<form:form commandName="recoveryForm" ...>
<form:input path="details" ... />
</form:form>
The commandName is key to telling the form the model object from which you will be pulling form values. In this case you are getting the details property from the RecoveryForm instance named recoveryForm. Make sense?
I use Play Framework 1.2.5 and use custom validation to a certain extend. I can't quite figure out how to do validation of a Map and report the error per field.
My entity has a description property, allowing the user to translate the description into any number of languages.
public class MyEntity extends Model {
...
#Valid
public Map<Locale, String> description;
...
}
Basically my form contain a textarea per locale.
<textarea rows="3" name="entity.description[en]" id="entity_description_en"></textarea>
<textarea rows="3" name="entity.description[da]" id="entity_description_da"></textarea>
I can get it to bind, but how do I validate the individual translations, and report any error on field level instead of just entity.description?
UPDATE:
I know that it can be done as part of the controller as seen below, but I would prefer if all validation was on the model only.
public static void create(#Valid MyEntity entity) {
validateMapKey("entity.description", entity.description, Locale.ENGLISH);
validateMapKey("entity.description", entity.description, new Locale("da"));
if(validation.hasErrors()) {
params.flash(); // add http parameters to the flash scope
validation.keep(); // keep the errors for the next request
index();
}
...
}
private static void validateMapKey(String f, Map<Locale, ? extends Object> v, Locale l) {
validation.required(String.format("%s[%s]", f, l), v.get(l));
}
#CheckWith annotation can help you..
#CheckWith(MyMapCheck.class)
public Map<Locale, String> description;
static class MyMapCheck extends Check {
public boolean isSatisfied(Object myEntityInstance, Object descriptionValue) {
return checkMyDescriptionAndReturnBoolean(description);
}
}
I have a field of type MultipartFile in a backing bean which is bound to a Spring form (I'm using MultipartFilter),
<form:form htmlEscape="false" action="${pageContext.request.contextPath}/admin_side/Category.htm" id="dataForm" name="dataForm" method="post" commandName="categoryBean" enctype="multipart/form-data">
<input type="file" id="txtCatImage" name="txtCatImage"/>
</form:form>
Backing Bean,
final public class CategoryBean
{
private MultipartFile txtCatImage=null;
public MultipartFile getTxtCatImage()
{
return txtCatImage;
}
public void setTxtCatImage(MultipartFile txtCatImage)
{
this.txtCatImage = txtCatImage;
}
}
I have tried to apply annotations like #NotEmpty but didn't work. They ended up with an exception.
javax.validation.UnexpectedTypeException: No validator could be found
for type: org.springframework.web.multipart.MultipartFile
I'm using Validation-API 1.0.0. Is this possible to perform a validation, if a user doesn't upload a file and press a submit button using HibernateValidator?
Now I understand what you are trying to accomplish specifically. Well you could implement your own custom validation. For example, instead of implementing the Spring validator interface, implement a Hibernate ConstraintValidator, for a specific annotation that you define for this specific case. Check this link. In this case you could add an implementation for a #NotNull validator for a MultipartFile object.
Putting constraint on bean method checking file on emptiness worked for me:
final public class CategoryBean
{
private MultipartFile txtCatImage = null;
public MultipartFile getTxtCatImage() { return txtCatImage; }
public void setTxtCatImage(MultipartFile txtCatImage) { this.txtCatImage = txtCatImage; }
#AssertTrue(message = "File must be provided")
public boolean isFileProvided() {
return (txtCatImage != null) && ( ! txtCatImage.isEmpty());
}
}
I'm having some trouble setting up validation for a form in spring.
The bean I would like to validate look like this:
public class RegistrationForm extends ProjectXUser {
#NotEmpty
private String password2;
#NotBlank
#AssertTrue
private Boolean agreedToConditions;
...
ProjectXUser inherits from BaseUser which has some more properties which are also annotated.
My controller looks like this:
#Controller
public class RegistrationController {
private static final String REGISTRATION_JSP = "registration";
#ModelAttribute("registrationForm")
public RegistrationForm getRegistrationForm() {
return new RegistrationForm();
}
#RequestMapping(value = { "/registratie/jaar", "registratie/proef" }, method = RequestMethod.GET)
public String year() {
return "registration";
}
#RequestMapping(value = { "/registratie/jaar", "registratie/proef" }, method = RequestMethod.POST)
public ModelAndView register(#Valid RegistrationForm registrationForm, BindingResult result) {
if (result.hasErrors()) {
return new ModelAndView(REGISTRATION_JSP);
} else {
return new ModelAndView("redirect:/registratie/success");
}
}
}
My spring configuration file contains:
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<mvc:annotation-driven />
I've read in the spring documentation that if a jsr-303 validator is present in the class path spring will detect it automatically and use it. So i've added hibernate-validator to my pom.
But when I debug my controller I can see the registrationForm contains the values I've filled in. But results always has 0 errors. Even if I enter some explicit wrong input in my form fields.
You need to return the result in the ModelAndView in the case where there are errors. All you are returning is an empty mav.
See: http://forum.springsource.org/showthread.php?117436-Spring-MVC-3-and-returning-validation-errors-to-page-from-Valid&highlight=bindingresult for an example.
If this bit of your code is firing and redirecting back to your registration page
if (result.hasErrors()) {
return new ModelAndView(REGISTRATION_JSP);
}
Then your JSR-303 validation is being picked up. You need to display your errors on your JSP page like this
<form:errors path="password2" cssClass="error" />
where cssClass="error" is the CSS you want to display the error with. It's automatically put into a <div> for you.