Kurt Koller
Kurt Koller

Reputation: 334

How to add ajax validation to programmatically generated primefaces component

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.

Upvotes: 0

Views: 3899

Answers (2)

V_K
V_K

Reputation: 226

Example of add onBlur event dynamically

   Message message=new Message();
    message.setId("msg");
    InputText it = new InputText();
    it.setId("input1");
    it.setRequired(true);
    message.setFor(it.getId());

    //******Setting validation render at onBlur event
    AjaxBehavior ajaxBehavior=new AjaxBehavior();
    ajaxBehavior.setAsync(true);
    ajaxBehavior.setUpdate(message.getId());
    it.addClientBehavior("blur", ajaxBehavior);
    //************************************************

Upvotes: 2

Kurt Koller
Kurt Koller

Reputation: 334

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://stackoverflow.com/a/7055586/1535568

Upvotes: 1

Related Questions