How to dynamically add JSF components

前端 未结 3 2066
-上瘾入骨i
-上瘾入骨i 2020-11-22 05:22

Can I add JSF components dynamically? I need to have a form with a button which should add one to the form. Is this possible?

I know

相关标签:
3条回答
  • 2020-11-22 06:02

    Use h:dataTable to add elements dynamically... Have a list of any type you want to provide values for dataTable...

    In h:dataTable... you can include the element tag to create inside <h:column>

    It will be used to generate elements you want to create dynamically.

    0 讨论(0)
  • 2020-11-22 06:06

    Use an iterating component like <h:dataTable> or <ui:repeat> to display a dynamically sized List of entities. Make the bean @ViewScoped to ensure that the list is remembered across postbacks on the same view instead of recreated over and over.

    Kickoff example with <h:dataTable> (when using <ui:repeat> simply replace <h:dataTable> by <ui:repeat>, and <h:column> by e.g. <li> or <div>):

    <h:form>
        <h:dataTable value="#{bean.items}" var="item">
            <h:column><h:inputText value="#{item.value}" /></h:column>
            <h:column><h:commandButton value="remove" action="#{bean.remove(item)}" /></h:column>
        </h:dataTable>
        <h:commandButton value="add" action="#{bean.add}" />
        <h:commandButton value="save" action="#{bean.save}" />
    </h:form>
    

    Managed bean:

    @Named
    @ViewScoped
    public class Bean {
    
        private List<Item> items;
    
        @PostConstruct
        public void init() {
            items = new ArrayList<>();
        }
    
        public void add() {
            items.add(new Item());
        }
    
        public void remove(Item item) {
            items.remove(item);
        }
    
        public void save() {
            System.out.println("items: " + items);
        }
    
        public List<Item> getItems() {
            return items;
        }
    
    }
    

    Model:

    public class Item {
    
        private String value;
    
        public String getValue() {
            return value;
        }
    
        public void setValue(String value) {
            this.value = value;
        }
    
        public String toString() {
            return String.format("Item[value=%s]", value);
        }
    
    }
    

    See also:

    • Recommended JSF 2.0 CRUD frameworks
    • How to create dynamic JSF form fields
    • How to implement a dynamic list with a JSF 2.0 Composite Component?
    • How to choose the right bean scope?
    0 讨论(0)
  • 2020-11-22 06:21

    It's should be like that

    Bind a form tag to the bean property

    
    <form binding="#{myBean.myform}">...</form>
    
    
    @ManagedBean("myBean")
    public class Bean{
       property HtmlForm myform;
    }

    on event, create a new instance of the input component

    HtmlInputText input=new HtmlInputText();

    and attach to the your form

    myform.getChildren().add(input);
    0 讨论(0)
提交回复
热议问题