Grails hasErrors方法与三元运算符? [英] Grails hasErrors method with ternary operator?

查看:507
本文介绍了Grails hasErrors方法与三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发使用Grails框架的应用程序,并且在从gsp视图中作为方法调用时遇到了hasErrors问题。

我有一个表单,可以通过数据库中的值填充(默认值)。这些值存储在会话对象中。用户可以编辑表单域中的值并将结果发送回数据库。在数据持续存在之前,我有一个验证数据的命令对象。如果存在错误,命令对象呈现视图时突出显示相同的表单和错误。



我想要做的是让表单字段由存储在会话中的值填充对象,除非命令对象有错误。在这种情况下,字段应该填入用户输入的错误值。



以下是代码片段:

 < g:textField name =somenameid =someidvalue =$ {hasErrors(bean:commandobject,field:'somename')?fieldValue(bean: commandobject,字段:'somename'):session.somevalue}/> 

上面代码的问题在于,无论输入的值是否正确,字段总是以来自会话对象的值结束。有没有解决这个问题的方法,或者我在第一时间做错了什么?

解决方案当您调用 hasErrors 就像你正在调用 < g:hasErrors /> 标记不会返回布尔值 - 它会查看条件并有条件调用标记正文 。在这个描述中,它是有道理的为什么它的行为方式。



我推荐的是创建自己的 TagLib 并使用 commandobject.errors.hasFieldErrors('somename') [docs] 在您的情况下(以获得您要查找的布尔值)。


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?

解决方案

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).

这篇关于Grails hasErrors方法与三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆