How to dynamically add JSF components

前端 未结 3 2205
-上瘾入骨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:06

    Use an iterating component like or 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 (when using simply replace by , and by e.g.

  • or
    ):

    
        
            
            
        
        
        
    
    

    Managed bean:

    @Named
    @ViewScoped
    public class Bean {
    
        private List 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 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?

提交回复
热议问题