Repeater

Repeater is an invisible container that is bound to a list of items (e.g. Products), and generates dynamic components for each item in the list.

As the Repeater iterates its items, it will allow one to dynamically construct UI components for each item.

Repeater will also ensure that its child components are properly indexed, meaning the rendered HTML markup will have the item's index appended to names and ID's.

A common use case for this is dynamic forms where certain UI aspects must be repeated a number of times. For example a form might have a text field where users can enter a category. But what if users can specify multiple categories? How many text fields should be rendered? In such scenarios the Repeater can render the field and two buttons, "Add" and "Remove" next to each field. This allows the user to dynamically add more text fields on the fly.

Example repeater:

ProductRepeater.java
public class ProductRepeater extends Repeater {

     /**
      * buildRow method must be implemented and acts as a template for each item.
      *
      * @param item (product) the current item which must be built
      * @param row the row for the current item
      * @param index the index of the current item
      */
     public void buildRow(final Object item, final RepeaterRow row, final int index) {

         // Each product will have a form to edit the product
         Form form = new Form("form") {
         row.add(form);

         FieldSet fieldSet = new FieldSet("product");
         form.add(fieldSet);

         fieldSet.add(new TextField("name")).setRequired(true);
         fieldSet.add(new DoubleField("price")).setRequired(true);

         Submit save = new Submit("save");
         save.setActionListener(new ActionListener() {
             public boolean onAction(Control source) {
                 return onSubmit(item, index);
             }
         });
         fieldSet.add(save);
    }

    /**
     * The onSubmit event
     */
    public boolean onSubmit(Object item, int index) {
        List products = getProducts();
        
        // Find the current items row in the repeater
        RepeaterRow row = (RepeaterRow) repeater.getControls().get(index);

        // Lookup the Form in the row
        Form form = (Form) container.getControl("form");

        if (form.isValid()) {

            // Copy the form values to the item
            form.copyTo(item);
        }
        return true;
    }
}

Example page:

RepeaterDemo.java
public RepeaterDemo extends Page {

    public void onInit() {
        Repeater repeater = new ProductRepeater("repeater");
        repeater.setItems(getProducts());
        addControl(repeater);
    }

    private List getProducts() {
        ...
    }
}

Other functionality include the ability to add a new item which automatically creates and builds a new row. Moving items up and down will also move the Repeaters row up and down.

  • No labels