【问题标题】:How to use ajax with Primefaces components programmatically如何以编程方式将 ajax 与 Primefaces 组件一起使用
【发布时间】:2018-11-26 21:05:55
【问题描述】:

我正在尝试以编程方式创建 Primefaces UIComponents,但不知何故我无法将数据获取到 Backing Bean。不确定是 Ajax 还是我为 InputText 设置的值。 我想以编程方式编写的代码:

<p:inputText id="id_test" value="#{myBean.value}">
    <p:ajax />
</p:inputText>

这是我尝试解决问题的方法:

private String value; // Getter&Setter


public void buildComponent(){
    FacesContext fc = FacesContext.getCurrentInstance();
    Application ap = fc.getApplication();

    InputText inputText = (InputText) ap.createComponent(fc, "org.primefaces.component.InputText", "org.primefaces.component.InputTextRenderer")
    inputText.setValue(value);
    inputText.setId("id_test");

    AjaxBehavior ajaxBehavior = (AjaxBehavior) ap.createBehavior(AjaxBehavior.BEHAVIOR_ID);
    inputText.addClientBehavior(inputText.getDefaultEventName(), behavior);
}

【问题讨论】:

  • 您已将具体的字符串值设置为InputText.setValue(),但您需要提供实际的ValueExpression。
  • 谢谢你帮我解决了。
  • 所以这里解决的实际问题与 Primefaces 和 AJAX 无关,可以简化为与 stackoverflow.com/questions/3510614/… 重复的问题
  • @Selaron 是的,你是对的。为我的无知道歉!
  • 不是问题,不是判断,只是结论。我们的开发人员一直在寻找最复杂的方向,即使根本原因就像打字错误一样简单;-)

标签: jsf primefaces


【解决方案1】:

您需要创建一个解析为您的 bean 属性的 ValueExpression。您的动态输入还应该如何知道将输入值发送到哪里?

代替:

inputText.setValue(value);

这样做:

ExpressionFactory expressionFactory = FacesContext.getCurrentInstance()
  .getApplication().getExpressionFactory();
ValueExpression veBinding = expressionFactory.createValueExpression("#{myBean.value}", String.class);
inputText.setValueExpression("value", veBinding);

【讨论】:

    【解决方案2】:

    我不确定您打算做什么,但是动态渲染组件而不是创建它可能会更好。类似的东西:

    <p:inputText id="id_test" value="#{myBean.value}" rendered="#{myBean.isSomeCondition">
        <p:ajax />
    </p:inputText>  
    

    <p:inputText id="id_test" value="#{myBean.value}" rendered="#{myBean.value != 'whatever'">
        <p:ajax />
    </p:inputText>  
    

    【讨论】:

    • 谢谢,但我面临的问题是我不知道我需要的输入组件的数量或类型。
    猜你喜欢
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多