问题
I'm developing application using Grails framework and I'm having problems with hasErrors when invoked as a method from a gsp view.
I have a form that get's populated by values from a database (default values). Those values are stored in a session object. Users can edit values in form fields and send results back to the database. Before data gets persisted I have a command object that validates data. If there are errors command objects renders view with the same form and errors highlighted.
What I'm trying to do is to have form fields populated by values stored in a session object unless there are errors from command object. In that case field(s) should be populated by the wrong values entered by the user.
Here's the code snippet:
<g:textField name="somename" id="someid" value="${hasErrors(bean: commandobject, field: 'somename') ? fieldValue(bean: commandobject, field: 'somename') : session.somevalue}" />
Problem with above code is that no matter the value entered in the field, whether be right or wrong, field always ends up with the value from the session object. Is there a solution to this or am I doing something wrong in the first place?
回答1:
When you call hasErrors
like that you're invoking the <g:hasErrors/> tag which doesn't return a boolean value - it looks at the condition and conditionally invokes the tag body. Under that description, it makes sense why it's behaving the way it is.
What I'd recommend is to create your own TagLib
and use commandobject.errors.hasFieldErrors('somename')
[docs] in your condition (to get the boolean value you're looking for).
回答2:
The hasErrors
as a method call in GSP works a bit differently than as a tag <g:hasErrors>
. The former is intended to set CSS class in divs or spans etc...
e.g. <div class="prop ${hasErrors(bean:parent, field:'child.name', 'errors')}">
where errors
is the CSS class name. So if you don't specify the output string, it seems to return false by default, so to workaround your case, return '1'. So your code should look like:
<g:textField name="somename" id="someid" value="${hasErrors(bean: commandobject, field: 'somename', '1') ? fieldValue(bean: commandobject, field: 'somename') : session.somevalue}" />
This will also work with logical operations in <g:if>
来源:https://stackoverflow.com/questions/7955589/grails-haserrors-method-with-ternary-operator