且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将Ajax验证添加到以编程方式生成的Primefaces组件

更新时间:2023-10-05 16:47:34

原来,我在看ajax组件时吠叫错误.今天我意识到我的组件也没有在提交时得到验证.事实证明,当动态创建JSF组件时,需要向该组件手动注册BeanValidator.感谢victor herrera对这个问题的回答: https://***.com/a/7055586/1535568 >

I am trying to attach normal bean validation to the blur event on a programmatically generated Primefaces UIComponent.

If I manually create the component using xhtml, which works fine, it looks like this:

<p:inputText id="customerName" value="#{editCustomerBean.name}" label="Name">
    <p:ajax async="true" event="blur" update="customerName, customerNameMsg" />
</p:inputText>

Unfortunately I need to generate this component on the fly because of some dynamic attributes that will be populated based on runtime data. The code I wrote to try and exactly replicate this component:

UIInput input = new InputText();

AjaxBehavior ajax = new AjaxBehavior();
ajax.setAsync(true);
ajax.setUpdate("customerName, customerNameMsg");
input.addClientBehavior("blur", ajax);
input.setId("customerName");
input.setValueExpression("value", expressionFactory.createValueExpression(elContext, "#{editCustomerBean.name}", String.class));

When I generate this component in this way, I see a request sent to the server on the blur event, but no validation takes place. The request which is posted looks identical to that which is sent when I specify the component in xhtml:

javax.faces.partial.ajax=true&javax.faces.source=mainForm%3AcustomerName&javax.faces.partial.execute=mainForm%3AcustomerName&javax.faces.partial.render=mainForm%3AcustomerName+mainForm%3AcustomerNameMsg&javax.faces.behavior.event=blur&javax.faces.partial.event=blur&mainForm%3AcustomerName=&javax.faces.ViewState=8176624577669857830%3A-4154840965136338204

I have seen similar questions posted on this website and the Primefaces forums, but it usually involves attaching a listener method to the AjaxBehavior, which is not what I am trying to do here. I would like the behavior to be the same as the tag when no listener is specified, which is to validate the field.

Turns out I was barking up the wrong tree looking at the ajax component. I realized today that my components were not being validated on submit either. It turns out that when you create your JSF components dynamically, you need to manually register the BeanValidator with the component. Thanks to victor herrera for his response to this question: https://***.com/a/7055586/1535568