Optional form fields in spring-mvc liferay portlet application - spring

I have a big form with a lot of date fields and int fields
my action phase methos is like this:
public void createCamapign(WebRequest request,ActionResponse response ,
Model model, #ModelAttribute("searchForm") CreateCampaignForm form) throws Exception{
where the form is my wrapper bean
anyway if i dont fill all the fields in the rendered form my application crashed with this error
[org.springframework.web.portlet.DispatcherPortlet] - Handler execution resulted in exception - forwarding to resolved error view
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'searchForm' on field 'activationDate': rejected value []; codes [typeMismatch.searchForm.activationDate,typeMismatch.activationDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [searchForm.activationDate,activationDate]; arguments []; default message [activationDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'activationDate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'activationDate': no matching editors or conversion strategy found]
how or where do i specify that these fields are optional
by the way in the case of int fields i kinda resolved it by using Integer class, but i dont want to do the same with Date type attributes

I am not sure if I understood your problem correctly. I am not an expert in Spring.
Just a suggestion, like can you make use of dependency check and #Required annotation to make a few fields necessary and other ignorable.

You could try to put the DateTimeFormat annotation on you date fields, like this:
#DateTimeFormat(pattern = "dd/mm/yyyy") // put any pattern you want
private Date myDate;
Note: If you are using a version of Spring older than 3.2, you need to add joda date library to your project classpath

Related

Thymeleaf and SpringBoot - Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for prope

I am building a web application using Thymeleaf and SpringBoot, I am new to both the technologies.
In my html file, there is a Date field as follows:
<input type="date" th:field="*{issueDate}" />
My model class has a field corresponding to issueDate as follows:
#NotNull(message = "Cannot be empty")
private Date issueDate;
When I input a date from the UI, I see the following exception in the browser:
Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property issueDate;
From my experience, I understand that the UI reads the property as a String, but the model expects a type Date due to which the error occurs. So I need to convert the String to a Date. However where should this be done? Since the error occurs even before the setter method in the model is invoked.
Any help would be much appreciated! Thanks in advance!
In your controller:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true));
}
WHERE "MM/dd/yyyy" is the date format you're using.

Cannot use spring validation with MongoDB [duplicate]

This question already has answers here:
How to I get Spring-Data-MongoDB to validate my objects?
(4 answers)
Closed 6 years ago.
I searched for solutions to validate data models in spring in Kotlin. But am not able to.
The following is the Tag data class.
data class Tag(#field:NotNull var name: String) {
lateinit #Id var id: ObjectId
}
I have enabled the configuration to use bean validation
#Configuration
open class ValidatorConfig {
#Bean
open fun validator() = LocalValidatorFactoryBean()
}
As per my knowledge, Spring Boot loads all the Bean Configuration automatically. And at runtime, when POSTed with empty Json, proper validation error should have been thrown but the following error is thrown
Instantiation of [simple type, class kagaz.sano.model.Tag] value failed for
JSON property name due to missing (therefore NULL) value for creator parameter
name which is a non-nullable type\n at [Source:
org.apache.catalina.connector.CoyoteInputStream#66f3b65c; line: 3, column: 1]
(through reference chain: kagaz.sano.model.Tag[\"name\"])
Spring validates objects by inspecting it's fields or properties values. To validate an object you need to first create it. When the json deserializer tries to parse input and create Tag instance it encounters and reports the problem:
Instantiation of [simple type, class kagaz.sano.model.Tag] value failed for
JSON property name
In order for Spring Validation to even start its work an instance of object is required - even if it is invalid.
This means that you'll need to allow for json deserializer to create an object in invalid state so that it can be inspected by validator like so:
data class TagDto(#get:NotNull var name: String? = null) {
#get:NotNull var id: ObjectId? = null
}

Spring-MVC bean Validation Type mismtach error

I am trying to validate an object using Spring JSR303 validation, i have a form object which have some nested objects along with some form properties here is my Form signature
public class PaymentDetailsForm
{
private AddressForm billingAddress;
// other properties and getter and setters
}
In my AddressForm bean i have used Bean validation annotations to validate data, but i am not using any #Valid annotation inside my PaymentDetailsForm for billingAddress.
This is the signature of my Controller method
public String createUpdatePaymentInfos(final Model model,
#ModelAttribute("paymentInfo") #Valid final PaymentDetailsForm form, final BindingResult bindingResult)
{
}
If i am sending correct data from the form everything is working perfectly fine, but if i omit any field from billingAddress which is marked as required or not null i am getting following binding error exception
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'paymentInfo' on field 'billingAddress':
rejected value [com.xxx.storefront.forms.AddressForm#e39f6f1,true];
codes [typeMismatch.paymentInfo.billingAddress,typeMismatch.billingAddress,typeMismatch.com.xxx.storefront.forms.AddressForm,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable:
codes [paymentInfo.billingAddress,billingAddress]; arguments []; default message [billingAddress]];
default message [Failed to convert property value of type 'java.lang.String[]'
to required type 'com.xxx.storefront.forms.AddressForm' for property 'billingAddress';
nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String[]] to required type [com.xxx.storefront.forms.AddressForm] for property 'billingAddress':
no matching editors or conversion strategy found]
I was expecting that since i have not used #valid annotation for billingAddress property, it should not be validated but even in case it get validated i am not able to understand above mentioned exception/error
The bindingResult that you are seeing doesn't look like it is because of validation errors, it is likely because of the binding errors - not being able to bind the UI fields to the inner billingAddress field. Even the binding errors would end up showing in the immediately following bindingresult argument like you are seeing.
That was due to some wrong mapping from UI,in my JSP page i was mapping address fields to billingAddress object but there was one hidden field like
<form:hidden path="billingAddress" id="billingAddress"/>
This was the cause of error since it was trying to send String array and Spring binding was unable to distinguish what i am trying to do

Spring MVC Data Binding Error

I'm getting the following error when I try to retrieve the form results in controller method:
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'search' on field 'clients': rejected value [14]; codes [typeMismatch.search.clients,typeMismatch.clients,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [search.clients,clients]; arguments []; default message [clients]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'clients'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.Client] for property 'clients[0]': no matching editors or conversion strategy found]
Model Object looks like this:
public class SearchForm {
private String name;
private List<Client> clients;
//getters and setters
}
public class Client {
private String name;
private Int id;
}
form:
<form:form method="POST", name="searchresults.html" modelattibute="search">
<form:input path="name"/>
<form:checkboxes path="clients" items="{clientsList}" itemsValue="id" itemsLabel="name"/>
</form:form>
this form displays the values correctly on the html page but when I click the submit button I get the above error
The browser will only send a list of client IDs when the form is submitted. How could Spring know how to convert each ID into a Client instance. You either have to tell it how to do, or add a List<String> clientIds property to your bean, and make the form:checkboxes tag use this property instead of clients as its path.

Wrapping PropertyEdtior exceptions during Spring validation

When I submit a Spring form and a PropertyEditor fails to convert a value, an exception is thrown and a message like this ends up in my validator errors object:
Failed to convert property value of type java.lang.String to required type
org.joda.time.DateMidnight for property startDate; nested exception is
java.lang.IllegalArgumentException: Invalid format: "2010-111" is malformed at "1"
Can I wrap this somehow, providing a friendlier message to display on screen?
I'm using #Valid in my controller, with the following in my form:
#NotNull
protected DateMidnight startDate;
Thanks
This error message has message codes such as typeMismatch.objectName.startDate (see DefaultMessageCodesResolver). To display a user-friendly message, you need to declare a MessageSource with the corresponding messages.

Resources