Open source cms for mobile and desktop websites

nive.forms

nive Form description

This class manages cms integration, field configuration, actions and form processing. Rendering, validation and data extraction is not included and requires a separate form library (nive.components.reform).

nive Forms can be connected to existing object or tool configurations and reuse all therein defined fields for forms. To setup a form like this use Setup(subset='action to handled') to load fields, actions, subsets automatically from the objects configuration.

A form does represent a single action but a set of form fields and multiple actions. nive forms can be rendered as subsets with a reduced selection of fields and different actions.

This is an example to be used in object view code:

form = ObjectForm(view=self, 
                  loadFromType=self.context.configuration)
form.Setup(subset="edit") 
# process and render the form.
result, data, action = form.Process()

view must be an instance of nive.views.BaseView. data will contain the rendered HTML whether the is loaded for the first time, validated ok or not. result will be false if the form input did not validate. The ObjectForm already includes all necessary functions to load data initially, create an object and store data for existing objects. All you have to do is switch the subset from edit to create.

form = ObjectForm(view=self,
                  loadFromType=self.context.configuration)
form.Setup(subset="create")
# process and render the form.
result, data, action = form.Process()

The configuration is loaded from the object configuration itself so all field settings are dynamically included. In fact the example above works for any object type.

Form action callback methods use the following footage:

def Method(self, action, **kw):
    # ...
    return result, data

These callback methods are automatically looked up and executed in Process(). Use action.method to link a method to a specific form action. Pass user as kw argument if the forms view attribute is None. If form.view is set view.User() is used to lookup the current user.

A custom HTMLForm example:

form = HTMLForm(view=self)
form.actions = [
    Conf(id="default",    method="StartForm",             name=u"Initialize",          hidden=True),
    Conf(id="create",     method="ReturnDataOnSuccess",   name=u"Create a new group",  hidden=False),
]
form.fields = [
    FieldConf(id="id",   name=u"Group id",   datatype="string", size="20", required=True),
    FieldConf(id="name", name=u"Group name", datatype="string", size="40", required=True)
]
form.Setup()
data, html, action = form.Process()

Callback for dynamic list item loading:

def loadGroups(fieldconf, object):
    return [{"id": id, "name":name}]


FieldConf(..., listItems=loadGroups, ...)

The build in progress bar is activated by default with a delay of 500 milliseconds. So it will only pop up if the form transmission takes some time e.g if a file upload is in progress. To disable the progress bar or skip the delay set the attribute HTMLForm.uploadProgressBar to none or always.

form = HTMLForm(view=self)
# disable the progress bar
form.uploadProgressBar = 'none' 

Please note: These form classes are for autogenerating forms. If you need more control over validation or rendering it might be easier to use a form library directly.

HTML form options

The following list describes all available form attributes and settings.

  • formid: (string) default = upload. The html element id applied to the form tag.

  • css_class: (string) default = form. The html element css class applied to the form tag.

  • actionPostfix: (string) default = $. Actions are triggered through form parameters. To prevent overlapping with

    field names action names are extended with a postfix e.g. create$

  • method: (string) default = POST. Either POST or GET. The HTTP method used for teh form.

  • action: (string) default = empty. The forms action url.

  • anchor: (string) default = empty. Adds an anchor to urls if set.

  • uploadProgressBar: (string) default = auto. Either auto, none or always. Defines when the progress bar is displayed.

  • use_ajax: (bool) default = False. Enable or disable ajax form submissions.

  • renderSuccess: (bool) default = True. If True the whole form will be rendered after successful submission. If False

    messages only will be returned.

  • successResponseBody: (string/callback) This option enables you to overwrite the complete response body on success. Use

    a callback to generate a dynamic response. The callback must take one parameter: the form instance and return a unicode string.

  • redirectSuccess: (string/callback) Redirect the browser to a new location on success. See below for a list of options.

  • redirectCancel: (string/callback) Redirect the browser to a new location on cancel. See below for a list of options.

Url placeholders to be used with redirectCancel and redirectSuccess. The placeholders are automatically resolved to a valid url for the current context

- obj_url
- obj_folder_url
- parent_url
- page_url
- page_url_anchor

redirectCancel and redirectSuccess can also be a callable. It is called with two parameters context and view class instance. E.g.

def makeUrl(context, view):
    return view.GetUrl(context) + "?query=" + view.GetFormValue('query')

Form styling options

By default 3 column form layouts are used. Each column can get a custom css class by setting e.g.

form.widget.settings["column1_css"] = "span4"
form.widget.settings["column2_css"] = "span8"
form.widget.settings["column3_css"] = "none"

To switch to a one column layout use the following code:

form.widget.item_template = "field_onecolumn"
form.widget.action_template = "form_actions_onecolumn"

Replacing default widgets or validators

FieldConf(id=”ftext”, datatype=”text”, size=1000, name=”ftext”,

# pass in a custom widget and settings as kw argument widget=”nive.components.reform.widget.FileToDataUploadWidget”, settings={“base64”: True},

# pass in a custom validator validator=myValidator

),

Control sets for Select and Radio fields

Conditional sets can be automatically shown and hidden by setting a lists option controlset:True and extending each listitem with a fields list.

FieldConf(id="flist",   
    datatype="list",   
    size=100,  
    name="flist", 
    settings={"controlset":True},
    listItems=[Conf(id="item 1", name="Item 1", 
                    fields=[FieldConf(id="ftext",datatype="text",size=10,name="ftext")]),
               Conf(id="item 2", name="Item 2", 
                    fields=[FieldConf(id="fnum",datatype="number",size=8,name="fnum")])
    ]
)

By default additional fields added as control fields will be treated as top level form fields. Control field data can be accessed like any other fields data. The controlset option is primarily a visual extension to make the more user friendly by showing some fields only in a certain context.

Example

Internally the form uses a structure like in the following manually defined form example

fields  = [
  FieldConf(id="ftext",   datatype="text",   size=1000, name="ftext", fulltext=1),
  FieldConf(id="fnumber", datatype="number", size=8,    name="fnumber", required=1),
  FieldConf(id="fdate",   datatype="datetime", size=8,  name="fdate"),
  FieldConf(id="flist",   datatype="list",   size=100,  name="flist", 
            listItems=[{"id": "item 1", "name":"Item 1"},
                       {"id": "item 2", "name":"Item 2"}]),
  FieldConf(id="fmselect", datatype="multilist", size=50, name="fmselect"),
]

actions = [
  Conf(id="default",    method="StartForm", name="Initialize", hidden=True),
  Conf(id="defaultEdit",method="LoadUser",  name="Initialize", hidden=True),
  Conf(id="create",     method="AddUser",   name="Create",     hidden=False),
  Conf(id="edit",       method="Update",    name="Edit",       hidden=False)
]

subsets = {
  "create": {"fields":  ["ftext", "fnumber", "fdate"], 
             "actions": ["create"],
             "defaultAction": "default"},
  "create2":{"fields":  ["ftext", "fnumber", "fdate", "flist", "fmselect"], 
             "actions": ["create"],
             "defaultAction": "default"},
  "edit":   {"fields":  ["ftext"], 
             "actions": ["edit"],
             "defaultAction": "defaultEdit"},
}

form = Form(view=self)
form.fields = fields
form.actions = actions
form.subsets = subsets
form.Setup(subset="create")
# validating data
result,data,errors = form.Validate(data)
class nive.forms.Form(view=None, loadFromType=None, context=None, request=None, app=None, **kw)

Base form class.

defaultSchemaFactory(form, fields, actions, force=False)

converts the fields to colander schema nodes including widget. If fielddef has node set and force is false node is used as widget. To overwrite set force = True.

SchemaNode(...)

Setup(subset=None)
  1. Load fields from object definition
  2. Loads subsets and actions from object form definition

Event - setup() after fields have been loaded

ApplyOptions(settings)

Applies a set of form settings to the current form. You can also pass in widget settings py prefixing the key with widget. E.g.

settings = {}
settings["widget.item_template"] = "field_onecolumn"
settings["widget.action_template"] = "form_actions_onecolumn"
Parameters:settings – dict with form settings
Returns:nothing
Validate(data, removeNull=True)

Extracts fields from request, converts and validates

Unlike the ValidateSchema() function Validate() validates html form widget data fields and does not support raw data validation.

Event - validate(data) before validate is called - process(data) after validate has succeeded, is not called if validate failed

returns bool, dictionary, list (result,data,errors)

ValidateSchema(data, removeNull=True)

Extracts fields from source data dictionary, converts and validates.

Unlike the Validate() function ValidateSchema() validates raw data and does not support html form widget data fields.

Event - validate(data) before validate is called

returns bool, dictionary, list (result,data,errors)

Extract(data, removeNull=True, removeEmpty=False)

Extract fields from request or source data dictionary and convert data types without validation.

returns bool, dictionary (result, data)

ExtractSchema(data, removeNull=False, removeEmpty=False)

Extract fields from request or source data dictionary and convert data types without validation.

returns bool, dictionary (result, data)

LoadObjData(obj=None)

Load data from existing object

Event - loadDataObj(data, obj) after data has been looked up

returns dict

LoadDefaultData()

Load default data from configuration

Event - loadDefault(data) after data has been looked up

returns dict

GetFields(removeReadonly=True)

Returns the list of field definitions. Readonly fields are removed by default.

returns list

GetActions(removeHidden=False)

Returns the list of form actions. Hidden actions are removed by default.

returns list

GetField(fieldid)

Get the field configuration by field id.

returns configuration or None

GetFormValue(key, request=None, method=None)

Extract single value from request

returns value

GetFormValues(request=None, method=None)

Extract all values from request

returns sict

ConvertFileUpload(key, method='post')

Convert a file upload to the internal File object

class nive.forms.HTMLForm(view=None, loadFromType=None, context=None, request=None, app=None, **kw)

Basic HTML Form

Process(**kw)

Processes the request and calls the required actions. kw parameter

defaultAction: default action if none found in request. Can also be configured in subset

redirectSuccess can be used to redirect on action success.

If renderSuccess is set to False the form itself will not be rendered if the action succeeds. Only the feedback message will be rendered.

Action definitions must define a callback method to process the action. The callback takes two parameters:

method(action, **kw)

returns bool, html, dict (result, data, action)

IsRequestAction(action)

Check request for the given action.

returns bool

RemoveActionsFromRequest()

Removes all actions from the request. If called before processing the form the default action will be used and the form never processed.

StartForm(action, **kw)

Default action. Use this function to initially render a form if: - startEmpty is True - defaultData is passed in kw - load form default data

Event - loadDefault(data) after data has been looked up

returns bool, html

StartRequestGET(action, **kw)

Default action. Initially loads data from request GET values. Loads default data for initial from display on object creation.

returns bool, html

StartRequestPOST(action, **kw)

Default action. Initially loads data from request POST values. Loads default data for initial from display on object creation.

returns bool, html

ReturnDataOnSuccess(action, **kw)

Process request data and returns validated data as result and rendered form as data. If validation fails result is False. redirectSuccess is ignored.

A custom success message can be passed as success_message as keyword.

returns bool, html

ProcessForm(action, **kw)

Process request data and returns validated data as result and rendered form as data. If validation fails result is False. redirectSuccess is ignored.

A custom success message can be passed as success_message as keyword.

returns bool, html

Cancel(action, **kw)

Cancel form action

Event - cancel() before validate is called

Used options: - redirectCancel

returns bool, string

Validate(data, removeNull=True)

Extracts fields from request or source data dictionary, converts and validates.

Event - validate(data) before validate is called - process(data) after validate has succeeded, is not called if validate failed

returns bool, dict, list (result,data,errors)

Extract(data, removeNull=False, removeEmpty=False)

Extracts fields from request or source data dictionary and converts data types without validation and error checking.

returns bool, dict (result, data)

Render(data, msgs=None, errors=None, messagesOnly=False, result=None)

renders the form with data, messages

messagesOnly=True will skip form and error rendering on just render the messages as html block.

Event - render(data) before the form is rendered

RenderBody(data, msgs=None, errors=None, result=None)

renders the form without header and footer

HTMLHead(ignore=(u'jquery.js', u'jquery-ui.js'))

Get necessary includes (js and css) for html header. Jquery and Jquery-ui are included by default in cmsview editor pages. So by default these two will be ignored.

class nive.forms.ObjectForm(view=None, loadFromType=None, context=None, request=None, app=None, **kw)

Contains actions for object creation and updates.

Supports sort form parameter pepos.

Setup(subset=None, addTypeField=False)

Calls Form.Setup() with the addition to automatically add the pool_type field.

  1. Load fields from object definition
  2. Loads subsets and actions from object form definition

Event - setup() after fields have been loaded

StartForm(action, **kw)

Default action. Called if no action in request or self.actions.default set. Loads default data for initial from display on object creation.

returns bool, html

StartFormRequest(action, **kw)

Default action. Called if no action in request or self.actions.default set. Loads default data from request for initial from display on object creation.

You can also pass additional default values for form fields as dictionary as kw[‘defaults’].

returns bool, html

StartObject(action, **kw)

Initially load data from object. context = obj

returns bool, html

UpdateObj(action, **kw)

Process request data and update object.

You can also pass additional values not used as form fields to be stored when the object is updated. Pass a dictionary as kw[‘values’].

Process() returns the form data as result if update succeeds.

Event - success(obj) after data has been successfully committed

returns form data or false, html or redirects

CreateObj(action, **kw)

Process request data and create object as child for current context.

Pass kw[‘pool_type’] to specify type to be created. If not passed pool_type will be extracted from data dictionary.

You can also pass additional values not used as form fields to be stored when the object is created. Pass a dictionary as kw[‘values’].

Process() returns the new object as result if create succeeds.

Event - success(obj) after data has been successfully committed

returns new object or none, html or redirects

class nive.forms.ToolForm(view=None, loadFromType=None, context=None, request=None, app=None, **kw)

Contains default actions for tool form processing.

Example

tool = app.GetTool("tool id", contextObject=app)
form = ToolForm(view=self, context=tool, loadFromType=tool.configuration)
form.Setup()
result, data, action = form.Process()

A simple example to render a tool form and execute it.

Setup(subset=None)
  1. Load fields from tool definition
  2. Loads subsets and actions from tool form definition

Event - setup() after fields have been loaded

RunTool(action, **kw)

Process request data and run tool.

returns bool, html

class nive.forms.WorkflowForm(view=None, loadFromType=None, context=None, request=None, app=None, **kw)

Contains default actions for workflow transition form processing Requires Form, HTMLForm or TemplateForm

CallWf(action, **kw)

process request data and call workflow transition for object. context = obj

class nive.forms.JsonMappingForm(view=None, loadFromType=None, context=None, request=None, app=None, **kw)

Maps form fields to a single dumped json text field json data is always stored as dictionary.

jsonDataField = the field to merge data to
mergeContext = if true the database values will be updated
               by form values

Process() returns the form data as dictionary on success.

Validate(data, removeNull=True)

Extracts fields from request or source data dictionary, converts and validates.

Event - validate(data) before validate is called - process(data) after validate has succeeded, is not called if validate failed

returns bool, dict, list (result,data,errors)

Extract(data, removeNull=False, removeEmpty=False)

Extracts fields from request or source data dictionary and converts data types without validation and error checking.

returns bool, dict (result, data)

StartObject(action, **kw)

Initially load data from configured object json data field. context = obj

returns bool, html

UpdateObj(action, **kw)

Process request data and update object.

Event - success(data) after data has been successfully committed

returns bool, html

class nive.forms.JsonSequenceForm(view=None, loadFromType=None, context=None, request=None, app=None, **kw)

Maps form fields as sequence to a single dumped json text field the sequence is always stored as list, json data as dictionary.

The form fields/values can be stored multiple times as sequence and the template offers options to add, delete and edit single items. Items in read only mode are not rendered by the form.

Sequence items are referenced by list position starting by 1.

jsonDataField = the field to merge data to

Process() returns the form data as dictionary on success.

StartObject(action, **kw)

Initially load data from configured object json data field. context = obj

Event - delete(data) after data has been deleted

returns bool, html

UpdateObj(action, **kw)

Process request data and update object.

Event - success(data) after data has been successfully committed

returns bool, html

nive.forms.MakeCustomizedViewForm(view, forContext, formSettingsOrSubset, typeconf=None, formClass=None, actions=None, defaultAction=None, defaultSettings=None, loadFromViewModuleConf=None)

Sets up from instances by looking up form sonfiguration settings in the various customization slots.

  1. typeconf.form defintion (if formSettingsOrSubset is a string)
  2. loadFromViewModuleConf.form
  3. actions and defaultAction
  4. defaultSettings
  5. formSettingsOrSubset (if it is a dict or configuration)
Parameters:
  • view – view class instance.
  • forContext – the context the view/for is rendered for
  • formSettingsOrSubset – form setup configuration or a subset name as string. If a string the subset is loaded from typeconf.form.subset.
  • typeconf – type configuration to load form fields referenced as string
  • formClass – on instantiated form class. defaults to nive.forms.ObjectForm
  • actions – list of possible actions to be used with the form. This has to be a list of action definitions.
  • defaultAction – the initial default action to be triggered if processed for the first time. Either a action definition or a string.
  • defaultSettings – a dict with default for the form. Can be oerriden by formSettings.
  • loadFromViewModuleConf – pass the view module configuration to load default form settings from ViewModuleConf.form.
Returns:

instantiated form class, subset name if used or None

exception nive.forms.ValidationError

Used for validation failures

© 2013 Nive GmbH