org.apache.click.extras.cayenne
Class CayenneForm

java.lang.Object
  extended by org.apache.click.control.AbstractControl
      extended by org.apache.click.control.AbstractContainer
          extended by org.apache.click.control.Form
              extended by org.apache.click.extras.cayenne.CayenneForm
All Implemented Interfaces:
Serializable, Control, Container, Stateful
Direct Known Subclasses:
TabbedCayenneForm

public class CayenneForm
extends Form

Provides Cayenne data aware Form control:   <form method='POST'>.

*
*
 
Cayenne is an Object Relational Mapping (ORM) framework. The CayenneForm supports creating (inserting) and saving (updating) Cayenne DataObject instances. This form will automatically apply the given data objects required and max length validation constraints to the form fields.

The CayenneForm uses the thread local DataContext obtained via DataContext.getThreadDataContext() for all object for persistence operations.

CayenneForm Examples

The example below provides a Department data object creation and editing page. To edit an existing department object, the object is passed to the page as a request parameter. Otherwise a new department object will be created when saveChanges() is called.
 public class OrganisationEdit extends Page {

   private CayenneForm form = new CayenneForm("form", Organisation.class);

    public OrganisationEdit() {
        form.add(new TextField("name", "Organisation Name:", 35);

        QuerySelect type = new QuerySelect("type", "Type:");
        type.setQueryValueLabel("organisation-types", "VALUE", "LABEL");
        form.add(type);

        form.add(new TextArea("description", "Description:", 35, 2);

        form.add(new Submit("ok", "   OK   ", this, "onOkClicked");
        form.add(new Submit("cancel", this, "onCancelClicked");

        form.setButtonAlign("right");
        addControl(form);
    }

    public void onGet() {
        Organisation organisation = (Organisation)
           getContext().getRequestAttribute("organisation");

        if (organisation != null) {
            form.setDataObject(organisation);
        }
    }

    public boolean onOkClicked() {
        if (form.isValid()) {
           if (form.saveChanges()) {
               Organisation organisation = (Organisation) form.getDataObject(false);
               String url = getContext().getPagePath(OrganisationViewer.class);
               setRedirect(url + "?id=" + organisation.getId());
               return false;
           }
        }
        return true;
    }

    public boolean onCancelClicked() {
        Organisation organisation = (Organisation) form.getDataObject(false);
        String url = getContext().getPagePath(OrganisationViewer.class);
        setRedirect(url + "?id=" + organisation.getId());
        return false;
    }
 } 
Note the getDataObject(false) method is used to obtain the DataObject from the Form without applying the field values to the data object. This is very important when dealing with already persistent objects and you don't want to apply any form changes.

Alternatively you can save a submitted DataObject using a Service or DAO pattern. For example:

    public boolean onOkClicked() {
        if (form.isValid()) {
           Organisation organisation = (Organisation) form.getDataObject();

           getOrganisationService().save(organisation);

           String url = getContext().getPagePath(OrganisationViewer.class);
           setRedirect(url + "?id=" + organisation.getId());
           return false;
        }
        return true;
    } 
Please Note if you are using this pattern with objects already saved, take care to ensure that the form submission is valid before calling getDataObject() as this method changes the DataObject's properties using the submitted form field values.

If you don't commit the changes at this point they will still be present in the session DataContext and will be applied in the next commitChanges() call, which may happen in a subsequent request. In these exceptional situations the object should be removed from the cache DataContext using invalidateObjects() method or by reloading the object from the database.

Alternatively use the DataContextFilter which will automatically rollback any uncommitted changes at the end of each request.

See Also:
Serialized Form

Field Summary
protected  HiddenField classField
          The data object class name hidden field.
protected  org.apache.cayenne.DataObject dataObject
          A transient dataObject handle for detecting a committed object.
static String FO_CLASS
          The form data object classname parameter name.
static String FO_ID
          The form data object id parameter name.
protected  boolean metaDataApplied
          The flag specifying that object validation meta data has been applied to the form fields.
protected  HiddenField oidField
          The data object id hidden field.
 
Fields inherited from class org.apache.click.control.Form
actionURL, ALIGN_CENTER, ALIGN_LEFT, ALIGN_RIGHT, buttonAlign, buttonList, buttonStyle, columns, defaultFieldSize, disabled, enctype, error, errorsAlign, errorsPosition, errorsStyle, fieldList, fieldStyle, fieldWidths, FOCUS_JAVASCRIPT, FORM_NAME, formSubmission, javaScriptValidation, labelAlign, labelsPosition, labelStyle, method, MULTIPART_FORM_DATA, POSITION_BOTTOM, POSITION_LEFT, POSITION_MIDDLE, POSITION_TOP, readonly, SUBMIT_CHECK, validate
 
Fields inherited from class org.apache.click.control.AbstractContainer
controlMap, controls
 
Fields inherited from class org.apache.click.control.AbstractControl
actionListener, attributes, behaviors, headElements, listener, listenerMethod, messages, name, parent, styles
 
Fields inherited from interface org.apache.click.Control
CONTROL_MESSAGES
 
Constructor Summary
CayenneForm()
          Create an CayenneForm with no name or dataObjectClass.
CayenneForm(Class dataObjectClass)
          Create a new CayenneForm with the given DataObject class.
CayenneForm(String name, Class dataObjectClass)
          Create a new CayenneForm with the given form name and DataObject class.
 
Method Summary
protected  void applyMetaData()
          Applies the DataObject validation database meta data to the form fields.
 void clearValues()
          Clear all the form field values setting them to null.
 org.apache.cayenne.access.DataContext getDataContext()
          Return the thread local DataContext obtained via DataContext.getThreadDataContext().
 org.apache.cayenne.DataObject getDataObject()
          Return a DataObject from the form with the form field values set on the object's properties.
 org.apache.cayenne.DataObject getDataObject(boolean copyTo)
          Return a DataObject from the form, with the form field values set on the object if the copyTo parameter is true.
 Class<? extends org.apache.cayenne.DataObject> getDataObjectClass()
          Return the Class of the form DataObject.
 Object getDataObjectPk()
          Return the DataObject primary key.
 Object getState()
          Return the CayenneForm state.
protected  boolean isPersistent(org.apache.cayenne.DataObject dataObject)
          Return true if the given dataObject is persistent.
 void onDestroy()
          Clear the cached dataObject and destroy the form fields.
 boolean onProcess()
          This method applies the object meta data to the form fields and then invokes the super.onProcess() method.
 void render(HtmlStringBuffer buffer)
          Render the HTML representation of the CayenneForm.
 boolean saveChanges()
          Save the object to the database committing all changes in the DataContext and return true.
 void setDataObject(org.apache.cayenne.DataObject dataObject)
          Set the given DataObject in the form, copying the object's properties into the form field values.
 void setDataObjectClass(Class dataObjectClass)
          Set the DataObject class.
 
Methods inherited from class org.apache.click.control.Form
add, add, add, add, clearErrors, copyFrom, copyFrom, copyTo, copyTo, endTag, getActionURL, getButtonAlign, getButtonList, getButtonStyle, getColumns, getControlSizeEst, getDefaultFieldSize, getEnctype, getError, getErrorFields, getErrorsAlign, getErrorsPosition, getErrorsStyle, getField, getFieldList, getFields, getFieldStyle, getFieldValue, getFieldWidths, getFormSizeEst, getHeadElements, getJavaScriptValidation, getLabelAlign, getLabelsPosition, getLabelStyle, getMethod, getTag, getValidate, hasPostError, insert, isDisabled, isFormSubmission, isJavaScriptValidation, isReadonly, isValid, onSubmitCheck, onSubmitCheck, onSubmitCheck, performSubmitCheck, remove, removeField, removeFields, removeState, renderButtons, renderControls, renderErrors, renderFields, renderFocusJavaScript, renderHeader, renderTagEnd, renderValidationJavaScript, replace, restoreState, saveState, setActionURL, setButtonAlign, setButtonStyle, setColumns, setDefaultFieldSize, setDisabled, setEnctype, setError, setErrorsAlign, setErrorsPosition, setErrorsStyle, setFieldStyle, setJavaScriptValidation, setLabelAlign, setLabelsPosition, setLabelStyle, setListener, setMethod, setName, setReadonly, setState, setValidate, startTag, validate, validateFileUpload
 
Methods inherited from class org.apache.click.control.AbstractContainer
contains, getControl, getControlMap, getControls, hasControls, onInit, onRender, renderChildren, renderContent, renderTagEnd, toString
 
Methods inherited from class org.apache.click.control.AbstractControl
addBehavior, addStyleClass, appendAttributes, dispatchActionEvent, getActionListener, getAttribute, getAttributes, getBehaviors, getContext, getHtmlImports, getId, getMessage, getMessage, getMessages, getName, getPage, getParent, getStyle, getStyles, hasAttribute, hasAttributes, hasBehaviors, hasStyles, isAjaxTarget, onDeploy, removeBehavior, removeStyleClass, renderTagBegin, setActionListener, setAttribute, setId, setParent, setStyle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface org.apache.click.Control
getBehaviors, getContext, getId, getMessages, getName, getParent, hasBehaviors, isAjaxTarget, onDeploy, setParent
 

Field Detail

FO_CLASS

public static final String FO_CLASS
The form data object classname parameter name.

See Also:
Constant Field Values

FO_ID

public static final String FO_ID
The form data object id parameter name.

See Also:
Constant Field Values

classField

protected HiddenField classField
The data object class name hidden field.


oidField

protected HiddenField oidField
The data object id hidden field.


metaDataApplied

protected boolean metaDataApplied
The flag specifying that object validation meta data has been applied to the form fields.


dataObject

protected transient org.apache.cayenne.DataObject dataObject
A transient dataObject handle for detecting a committed object.

Constructor Detail

CayenneForm

public CayenneForm(String name,
                   Class dataObjectClass)
Create a new CayenneForm with the given form name and DataObject class.

Parameters:
name - the form name
dataObjectClass - the DataObject class

CayenneForm

public CayenneForm(Class dataObjectClass)
Create a new CayenneForm with the given DataObject class.

Parameters:
dataObjectClass - the DataObject class

CayenneForm

public CayenneForm()
Create an CayenneForm with no name or dataObjectClass.

Important Note the form's name and dataObjectClass must be defined before it is valid.

Method Detail

clearValues

public void clearValues()
Clear all the form field values setting them to null. This method will not clear the Form Object Class ("FO_CLASS") hidden field value.

Overrides:
clearValues in class Form
See Also:
Form.clearValues()

getDataContext

public org.apache.cayenne.access.DataContext getDataContext()
Return the thread local DataContext obtained via DataContext.getThreadDataContext().

Returns:
the thread local DataContext

getDataObject

public org.apache.cayenne.DataObject getDataObject(boolean copyTo)
Return a DataObject from the form, with the form field values set on the object if the copyTo parameter is true.

Once the data object has been obtained it will be cached for the duration of the request so that subsequent calls to this method will return the same instance rather than creating new data object instances.

Parameters:
copyTo - option to copy the form properties to the returned data object
Returns:
the data object from the form with the form field values applied to the data object properties.

getDataObject

public org.apache.cayenne.DataObject getDataObject()
Return a DataObject from the form with the form field values set on the object's properties.

Once the data object has been obtained it will be cached for the duration of the request so that subsequent calls to this method will return the same instance rather than creating new data object instances.

Returns:
the DataObject with the Form field values applied to the object

setDataObject

public void setDataObject(org.apache.cayenne.DataObject dataObject)
Set the given DataObject in the form, copying the object's properties into the form field values. If the given data object is null any form field values will be cleared, excluding hidden fields.

Parameters:
dataObject - the DataObject to set

getDataObjectClass

public Class<? extends org.apache.cayenne.DataObject> getDataObjectClass()
Return the Class of the form DataObject.

Returns:
the Class of the form DataObject.

setDataObjectClass

public void setDataObjectClass(Class dataObjectClass)
Set the DataObject class.

Parameters:
dataObjectClass - the DataObject class

getDataObjectPk

public Object getDataObjectPk()
Return the DataObject primary key.

Returns:
the DataObject primary key

getState

public Object getState()
Return the CayenneForm state.

Specified by:
getState in interface Stateful
Overrides:
getState in class Form
Returns:
the state of input Fields and FieldSets contained in the form
See Also:
Form

saveChanges

public boolean saveChanges()
Save the object to the database committing all changes in the DataContext and return true. If a ValidationException occurred then all DataContext changes will be rolled back, the validation error will be set as the Form's error and the method will return false.

If no DataObject is added to the form using setDataObject() then this method will:

If an existing persistent DataObject is added to the form using setDataObject() then this method will:

Returns:
true if the DataObject was saved or false otherwise

onProcess

public boolean onProcess()
This method applies the object meta data to the form fields and then invokes the super.onProcess() method.

Specified by:
onProcess in interface Control
Overrides:
onProcess in class Form
Returns:
true to continue Page event processing or false otherwise
See Also:
Form.onProcess()

onDestroy

public void onDestroy()
Clear the cached dataObject and destroy the form fields.

Specified by:
onDestroy in interface Control
Overrides:
onDestroy in class Form
See Also:
Form.onDestroy()

render

public void render(HtmlStringBuffer buffer)
Render the HTML representation of the CayenneForm.

This method applies the object meta data to the form fields and then invokes the super.toString() method.

Specified by:
render in interface Control
Overrides:
render in class Form
Parameters:
buffer - the specified buffer to render the control's output to
See Also:
AbstractContainer.toString()

applyMetaData

protected void applyMetaData()
Applies the DataObject validation database meta data to the form fields.

The field validation attributes include:


isPersistent

protected boolean isPersistent(org.apache.cayenne.DataObject dataObject)
Return true if the given dataObject is persistent.

Parameters:
dataObject - the DataObject to test
Returns:
true if the given dataObject is persistent