如何将ajax添加到动态创建的primefaces输入字段

时间:2014-03-01 09:32:38

标签: ajax primefaces

我想创建一个页面,允许用户更新mysql表。客户端管理员可以更改此表,因此我必须阅读表模式并动态创建字段。我从How to create dynamic JSF form fields获得了基本代码,并从How to add ajax validation to programmatically generated primefaces component获得了ajax代码。

要创建概念证明页面,我使用以下代码(注意,我正在使用primefaces):

   for (int idx = 1; idx < 3; idx++) {
        UIInput input = new InputText();
        input.setId("text" + idx); 
        ValueExpression targetExpression = facesContext.getApplication().getExpressionFactory().createValueExpression(facesContext.getELContext(), "#{viewMakeFields.value}", String.class);
        input.setValueExpression("value", targetExpression);
        AjaxBehavior ab = new AjaxBehavior();
        ab.setAsync(true);
        ab.setProcess("text"+idx);
        input.addClientBehavior("blur", ab); // "change" doesn't work either
        form.getChildren().add(input);
    }

然后,在getter和setter中,我获取组件ID以识别哪个字段已更改:

public static String getCallingComponentID() {
    UIComponent component = UIComponent.getCurrentComponent(FacesContext.getCurrentInstance());
    return component.getId();
}

public String getValue() {
    String id = getCallingComponentID();
    System.out.println("getValue " + id);
    return text1;
}

public void setValue(String text1) {
    String id = getCallingComponentID();
    System.out.println("setValue " + id);
    this.text1 = text1;
}

ajax没有触发,当我点击提交按钮时,我得到了(我知道混合部分和完整提交并不好):

INFO:   getValue text1
INFO:   getValue text2
INFO:   getValue text1
INFO:   getValue text2
INFO:   setValue j_id1
INFO:   setValue j_id1
INFO:   getValue text1
INFO:   getValue text2

我看到两种可能的解决方案:让ajax工作,以便调用setter的组件具有正确的id或获取表单submit以识别哪个子节点正在调用setter。前者是首选,因为我想要禁用保存按钮,直到某些内容发生变化,但此时我愿意接受后者。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

原来这个代码确实有效。在我蜿蜒的某个地方,错误发生了变化,我并不了解其中的重要性。用h:替换头部在xhtml文件中我添加了字段以使ajax工作。