1.6. Simple Form Example

The Form and Field controls are also some of the most commonly used controls in the Click Framework.

The SimpleForm page below provides a demonstration of using these controls.

In our example code we have the page's constructor adding a TextField field and a Submit button to the form. A page method is also set as a control listener on the form. Also note in this example the page's public form field is automatically added to its list of controls.

public class SimpleForm extends Page {

    private Form form = new Form("form");

    // Constructor ------------------------------------------------------------

    public SimpleForm() {
        addControl(form);

        form.add(new TextField("name", true));
        form.add(new Submit("OK"));

        form.setListener(this, "onSubmit");
    }

    // Event Handlers ---------------------------------------------------------

    /**
     * Handle the form submit event.
     */
    public boolean onSubmit() {
        if (form.isValid()) {
            msg = "Your name is " + form.getFieldValue("name");
        }
        return true;
    }
}

Next we have the SimpleForm template simple-form.htm. The Click application automatically associates the simple-form.htm template with the SimpleForm class.

<html>
  <head>
    $headElements
  </head>
  <body>

    $form

    #if ($msg)
      <div id="msgDiv"> $msg </div>
    #end

    $jsElements

  </body>
</html>

When the SimpleForm page is first requested the $form object will automatically render itself as:

Simple Form

Figure 1.4. Simple Form


Say the user does not enter their name and presses the OK button to submit the form. The ClickServlet creates a new SimpleForm page and processes the form control.

The form control processes its fields and determines that it is invalid. The form then invokes the listener method onSubmit(). As the form is not valid this method simply returns true and the form renders the field validation errors.

Form after an invalid request

Figure 1.5. Form after an invalid request


Note the form will automatically maintain the entered state during the post and validate cycle.

Now if the user enters their name and clicks the OK button, the form will be valid and the onSubmit() add a msg to the Pages model. This will be rendered as:

Form after a valid request

Figure 1.6. Form after a valid request