net.sf.click.extras.cayenne
Class CayenneForm

java.lang.Object
  extended bynet.sf.click.control.AbstractControl
      extended bynet.sf.click.control.AbstractContainer
          extended bynet.sf.click.control.Form
              extended bynet.sf.click.extras.cayenne.CayenneForm
All Implemented Interfaces:
Container, Control, Serializable
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 dont 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.

Author:
Malcolm Edgar, Andrus Adamchik
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.
protected static String FO_CLASS
          The form data object classname parameter name.
protected 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 net.sf.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, HTML_IMPORTS, javaScriptValidation, labelAlign, labelsPosition, labelStyle, method, MULTIPART_FORM_DATA, POSITION_BOTTOM, POSITION_LEFT, POSITION_MIDDLE, POSITION_TOP, readonly, SUBMIT_CHECK, validate
 
Fields inherited from class net.sf.click.control.AbstractContainer
controlMap, controls
 
Fields inherited from class net.sf.click.control.AbstractControl
actionListener, attributes, listener, listenerMethod, messages, name, parent, styles
 
Fields inherited from interface net.sf.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 getDataObjectClass()
          Return the Class of the form DataObject.
 Object getDataObjectPk()
          Return the DataObject primary key.
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.
protected  void setObjEntityFieldConstrains(String relationshipName, org.apache.cayenne.map.ObjEntity objEntity)
          Set the ObjEntity meta data constraints on the form fields.
 
Methods inherited from class net.sf.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, getHtmlImports, getJavaScriptValidation, getLabelAlign, getLabelsPosition, getLabelStyle, getMethod, getTag, getValidate, hasPostError, insert, isDisabled, isFormSubmission, isReadonly, isValid, onSubmitCheck, onSubmitCheck, onSubmitCheck, performSubmitCheck, remove, removeField, removeFields, renderButtons, renderControls, renderErrors, renderFields, renderFocusJavaScript, renderHeader, renderTagEnd, renderValidationJavaScript, setActionURL, setButtonAlign, setButtonStyle, setColumns, setDefaultFieldSize, setDisabled, setEnctype, setError, setErrorsAlign, setErrorsPosition, setErrorsStyle, setFieldStyle, setJavaScriptValidation, setLabelAlign, setLabelsPosition, setLabelStyle, setListener, setMethod, setName, setReadonly, setValidate, startTag, validate
 
Methods inherited from class net.sf.click.control.AbstractContainer
contains, getControl, getControlMap, getControls, hasControls, onInit, onRender, renderChildren, renderContent, renderTagEnd, toString
 
Methods inherited from class net.sf.click.control.AbstractControl
addStyleClass, appendAttributes, getActionListener, getAttribute, getAttributes, getContext, getId, getMessage, getMessage, getMessage, getMessages, getName, getPage, getParent, getStyle, getStyles, hasAttribute, hasAttributes, hasStyles, onDeploy, registerActionEvent, 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 net.sf.click.Control
getContext, getId, getMessages, getName, getParent, onDeploy, setParent
 

Field Detail

FO_CLASS

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

See Also:
Constant Field Values

FO_ID

protected 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 forms'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.

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 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

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.

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.

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.

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

setObjEntityFieldConstrains

protected void setObjEntityFieldConstrains(String relationshipName,
                                           org.apache.cayenne.map.ObjEntity objEntity)
Set the ObjEntity meta data constraints on the form fields.

Parameters:
relationshipName - the object relationship name, null if the ObjEntity of the CayenneForm
objEntity - the ObjEntity to lookup meta data from