在JSF中动态添加文本字段 [英] Dynamic adding text fields in JSF

查看:63
本文介绍了在JSF中动态添加文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有inputText的屏幕,旁边有一个(+)按钮,当用户应按该按钮时,表单应在其旁边(或下方,无论如何)添加另一个额外的inputText

I have a screen with inputText, beside it there's a (+) button, when the user should press that button the form should add another extra inputText beside it (or below, whatever)

这是代码:

<table>
  <tr>
    <td>
      <p:inputText value="#{controller.x}" />
      <img src="../images/ico_plus.png" />
    </td>
  </tr>
</table>

在Controller.java中:

in Controller.java:

private String x;

public String getX(){return x}
public void setX(String val){x = val}

我需要在页面上填充多个字段,并且控制器需要提取所有字段值

I need the page to be populated with multiple fields and the controller to have all the fields values' fetched

推荐答案

这个问题已经回答了不止一次,基本上,您需要为bean中的所有字段都保留一个List,然后将其删除或添加到List与您的按钮.请注意,这对于位于ViewScopedSessionScoped中非常重要,否则您的List将在每次操作时重置.

This question was answered more than one time, basically you need to keep a List for all fields in the bean, and you remove or add to this List with your buttons. Note this is important to be in ViewScoped or SessionScoped ortherwise your List will be reset at every actions.

查看:

<h:form>
    <h:dataTable id="tblFields" value="#{bean.fields}" var="field">
        <h:column>
            <h:inputText value="#{field.value}" />
        </h:column>

        <h:column>
            <h:commandButton value="Remove">
                <f:ajax listener="#{bean.onButtonRemoveFieldClick(field)}" immediate="true" render="@form" /> 
            </h:commandButton>
        </h:column>
    </h:dataTable>

    <h:commandButton value="Add">
        <f:ajax listener="#{bean.onButtonAddFieldClick}" execute="@form" render="tblFields" /> 
    </h:commandButton>
</h:form>

帮助程序类:

public class Field implements Serializable
{
    private String m_sName;

    public void setName(String p_sName)
    {
        m_sName = p_sName;
    }

    public String getName()
    {
        return m_sName;
    }
}

Bean:

@ManagedBean
@ViewScoped
public class Bean implements Serializable
{
    private List<Field> m_lFields;

    public Bean()
    {
        m_lFields = new ArrayList();

        m_lFields.add(new Field());
    }

    public void setFields(List<Field> p_lFields)
    {
        m_lFields = p_lFields;
    }

    public List<Field> getFields()
    {
        return m_lFields;
    }

    public void onButtonRemoveFieldClick(final Field p_oField)
    {
        m_lFields.remove(p_oField);
    }

    public void onButtonAddFieldClick(AjaxBehaviorEvent p_oEvent)
    {
        m_lFields.add(new Field());
    }
}

这篇关于在JSF中动态添加文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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