Forms API

Form

class Form([kwargs])

Extends BaseForm() and registers DeclarativeFieldsMeta() as a mixin to be used to set up Fields when this constructor is extended.

This is intended intended as the entry point for defining your own forms.

You can do this using its static extend() function, which is provided by Concur.

Form.extend(prototypeProps[, constructorProps])

Creates a new constructor which inherits from Form.

Arguments:
  • prototypeProps (Object) – form Fields and other prototype properties for the new form, such as a custom constructor and validation methods.
  • constructorProps (Object) – properties to be set directly on the new constructor function.
DeclarativeFieldsMeta(prototypeProps[, constructorProps])

This mixin function is responsible for setting up form fields when a new Form constructor is being created.

It pops any Fields it finds off the form’s prototype properties object, determines if any forms are also being mixed-in via a __mixin__ property and handles inheritance of Fields from any form which is being directly extended, such that fields will be given the following order of precedence should there be a naming conflict with any of these three sources:

  1. Fields specified in prototypeProps
  2. Fields from a mixed-in form
  3. Fields from the Form being inherited from

If multiple forms are provided via __mixin__, they will be processed from left to right in order of precedence for mixing in fields and prototype properties.

Forms can prevent fields from being inherited or mixed in by adding a same-named property to their prototype, which isn’t a Field. It’s suggested that you use null as the value when shadowing to make this intent more explicit.

BaseForm

class BaseForm([kwargs])

A collection of Fields that knows how to validate and display itself.

Arguments:
  • kwargs (Object) – form options, which are as follows:
  • kwargs.data (Object) – input form data, where property names are field names. A form with data is considered to be “bound” and ready for use validating and coercing the given data.
  • kwargs.files (Object) – input file data.
  • kwargs.validation

    Configures form-wide interactive validation when the user makes changes to form inputs in the browser. This can be a String, or an Object which configures default validation for form inputs.

    If 'manual', validation will not be performed – you are responsible for hooking up validation and using methods such as setData() and isValid() to perform all validation. This is the default setting.

    If 'auto', text fields will, by default be validated when the onChange event fires, with a 250 millisecond delay from the last user input to the validation being performed.

    If an Object is given, it should have the following properties:

    event
    The name of the default event to use to trigger validation. This should be in camelCase format, as used by React. For example, if 'onBlur', text input validation will be performed when the input loses focus after editing.
    delay
    A delay, in milliseconds, to be used to debounce performing of validation, to give the user time to enter input without distracting them with error messages or other change in how the input’s displayed while they’re still typing.

    If any String but 'manual' or 'auto' is given, it will be used as if it were passed as the event property of an Object.

    For example, passing {validation: 'onChange'} will cause each form inputs to trigger validation as soon as the user makes any change.

    New in version 0.6.

  • kwargs.controlled (Boolean) –

    Configures whether or not the form will render controlled components - when using controlled components, you can update the values displayed in the form post initial render using form.setData() or form.updateData()

    New in version 0.6.

  • kwargs.onStateChange (Function) –

    If interactive validation is configured for a Form or any of its Fields, this callback function must be provided, or an Error will be thrown.

    It will be called any time the form’s input data or validation state changes as the result of user input.

    Typically, this function should at least force React to update the component in which the Form is being rendered, to display the latest validation state to the user from the last change they made to the form.

    New in version 0.6.

  • kwargs.autoId (String) – a template for use when automatically generating id attributes for fields, which should contain a {name} placeholder for the field name – defaults to id_{name}.
  • kwargs.prefix (String) – a prefix to be applied to the name of each field in this instance of the form - using a prefix allows you to easily work with multiple instances of the same Form object in the same HTML <form>, or to safely mix Form objects which have fields with the same names.
  • kwargs.initial (Object) – initial form data, where property names are field names – if a field’s value is not specified in data, these values will be used when initially rendering field widgets.
  • kwargs.errorConstructor (Function) – the constructor function to be used when creating error details. Defaults to ErrorList().
  • kwargs.labelSuffix (String) – a suffix to be used when generating labels in one of the convenience methods which renders the entire Form – defaults to ':'.
  • kwargs.emptyPermitted (Boolean) – if true, the form is allowed to be empty – defaults to false.

Instance Properties

Form options documented in kwargs above are all set as instance properties.

The following instance properties are also available:

form.fields

Form fields for this instance of the form.

Since a particular instance might want to alter its fields based on data passed to its constructor, fields given as part of the form definition are deep-copied into fields every time a new instance is created.

Instances should only ever modify fields.

Note

fields does not exist until the BaseForm constructor has been called on the form instance that’s being constructed.

This is important to note when you intend to dynamically modify fields when extending a form – you must call the constructor of the form which has been extended before attempting to modify fields.

Type:Object with field names as property names and Field instances as properties.
form.isInitialRender

Determines if this form has been given input data which can be validated.

true if the form has data or files set.

form.cleanedData

After a form has been validated, it will have a cleanedData property. If your data does not validate, cleanedData will contain only the valid fields.

Type:Object with field names as property names and valid, cleaned values coerced to the appropriate JavaScript type as properties.

Prototype Functions

Prototype functions for validating and getting information about the results of validation:

BaseForm#validate(form)

Gets input data from the <form> containing this Form’s rendered widgets and validates it.

Arguments:
  • form – a <form> DOM node – if React’s representation of the <form> is given, its getDOMNode() function will be called to get the real DOM node.
Returns:

true if the <form> data is valid, false otherwise.

New in version 0.6.

BaseForm#reset([initialData])

Resets the form to its initial render state, optionally giving it new initial data.

Arguments:
  • initialData (Object) – new initial data for the form.

New in version 0.6.

BaseForm#setData(data[, kwargs])

Replaces the form’s form.data with the given data (and flips form.isInitialRender to false, if necessary) and triggers form cleaning and validation, returning the result of form.isValid().

Arguments:
  • data (Object) – new input data for the form
  • kwargs (Object) – data updating options, which are as follows:
  • kwargs.prefixed (Boolean) –

    pass true when updating data in a prefixed form and the field names in data are already prefixed – defaults to false

    New in version 0.6.

Returns:

true if the form has no errors after validating the updated data, false otherwise.

New in version 0.5.

BaseForm#setFormData(formData)

Replaces with form’s input data with data extracted from a <form> (i.e. with formData()).

When using multiple forms with prefixes, form data will always be prefixed - using this method when working with manually extracting form data should ensure there are no surprises if moving from non-prefixed forms to prefixed forms.

Arguments:
  • formData (Object) –
    new input data for the form, which has been extracted from a <form>

    New in version 0.6.

BaseForm#updateData(data[, kwargs])

Updates the form’s form.data (and flips form.isInitialRender to false, if necessary).

By default, triggers validation of fields which had their input data updated, as well as form-wide cleaning.

Arguments:
  • data (Object) –

    partial input data for the form, field name -> input data.

    If your form has a prefix, field names in the given data object must also be prefixed.

  • kwargs (Object) – data updating options, which are as follows:
  • kwargs.prefixed (Boolean) – pass true when updating data in a prefixed form and the field names in data are already prefixed – defaults to false

The follwing options are intended for use with controlled forms, when you’re only updating data in order to change what’s displayed in the controlled components:

Arguments:
  • kwargs.validate (Boolean) – pass false if you want to skip validating the updated fields – defaults to true. This can be ignored if you’re passing known-good data.
  • kwargs.clearValidation (Boolean) – pass false if you’re skipping validation and you also want to skip clearing of the results of any previous validation on the fields being updated, such as error messages and cleanedData – defaults to true

New in version 0.6.

BaseForm#isComplete()

Determines whether or not the form has errors and valid input data for all required fields, triggering cleaning of the form first if necessary.

This can be used to indicate to the user that a form which is being validated as they fill it in is ready for submission.

The distinction between isComplete() and BaseForm#isValid() is that a form which has had, for example, a single field filled in and validated is valid according to the partial validation which has been performed so far (i.e. it doesn’t have any error messages) but isn’t yet complete.

Returns:true if the form has input data and has no errors, and there is cleanedData present for every required field on the form.

New in version 0.6.

BaseForm#isValid()

Determines whether or not the form has errors, triggering cleaning of the form first if necessary.

When user input is being incrementally validated as it’s given, this function gives you the current state of validation (i.e. whether or not there are any errors). It will not reflect the validity of the whole form until a method which performs whole-form validation (BaseForm#validate() or setData()) has been called.

Returns:true if the form is has input data and has no errors, false otherwise. If errors are being ignored, returns false.
BaseForm#errors()

Getter for validation errors which first cleans the form if there are no errors defined yet.

Returns:validation errors for the form, as an ErrorObject()
BaseForm#nonFieldErrors()
Returns:errors that aren’t associated with a particular field - i.e., errors generated by BaseForm#clean(), or by calling BaseForm#addError() and passing null instead of a field name. Will be an empty error list object if there are none.
BaseForm#hasChanged()
Returns:true if data differs from initial, false otherwise.
BaseForm#changedData()
Returns:a list of the names of fields which have differences between their initial and currently bound values.
BaseForm#fullClean()

Validates and cleans forms.data and populates errors and cleanedData.

You shouldn’t need to call this function directly in general use, as it’s called for you when necessary by BaseForm#isValid() and BaseForm#errors().

BaseForm#partialClean(fieldNames)

Validates and cleans form.data for the given field names and triggers cross-form cleaning in case any form.cleanedData it uses has changed.

Arguments:
  • fieldNames (Array) – a list of unprefixed field names.
BaseForm#clean()

Hook for doing any extra form-wide cleaning after each Field’s Field#clean() has been called. Any ValidationError() thrown by this method will not be associated with a particular field; it will have a special-case association with the field named '__all__'.

If you override this method and return something from it, the returned value will be used as the new cleanedData.

BaseForm#addError(field, error)

This function allows adding errors to specific fields from within the form.clean() method, or from outside the form altogether. This is a better alternative to fiddling directly with form._errors, which we shouldn’t even be mentioning in here, whoops...

The field argument is the name of the field to which the errors should be added. If its value is null the error will be treated as a non-field error as returned by form.nonFieldErrors().

The error argument can be a simple string, or preferably an instance of ValidationError().

Note that form.addError() automatically removes the relevant field from form.cleanedData.

New in version 0.5.

A number of default rendering functions are provided to generate ReactElement representations of a Form’s fields.

These are general-purpose in that they attempt to handle all form rendering scenarios and edge cases, ensuring that valid markup is always produced.

For flexibility, the output does not include a <form> or a submit button, just field labels and inputs.

BaseForm#render()

Default rendering method, which calls BaseForm#asTable()

New in version 0.5.

BaseForm#asTable()

Renders the form as a series of <tr> tags, with <th> and <td> tags containing field labels and inputs, respectively.

You’re responsible for ensuring the generated rows are placed in a containing <table> and <tbody>.

BaseForm#asUl()

Renders the form as a series of <li> tags, with each <li> containing one field. It does not include the <ul> so that you can specify any HTML attributes on the <ul> for flexibility.

BaseForm#asDiv()

Renders the form as a series of <div> tags, with each <div> containing one field.

New in version 0.5.

Prototype functions for use in rendering form fields.

BaseForm#boundFields([test])

Creates a BoundField() for each field in the form, in the order in which the fields were created.

Arguments:
  • test (Function(field,name)) – If provided, this function will be called with field and name arguments - BoundFields will only be generated for fields for which true is returned.
BaseForm#boundFieldsObj([test])

A version of BaseForm#boundFields() which returns an Object with field names as property names and BoundFields as properties.

BaseForm#boundField(name)

Creates a BoundField() for the field with the given name.

Arguments:
  • name (String) – the name of a field in the form.
BaseForm#hiddenFields()
Returns:a list of BoundField() objects that correspond to hidden fields. Useful for manual form layout.
BaseForm#visibleFields()
Returns:a list of BoundField() objects that do not correspond to hidden fields. The opposite of the BaseForm#hiddenFields() function.
BaseForm#isMultipart()

Determines if the form needs to be multipart-encoded in other words, if it has a FileInput().

Returns:true if the form needs to be multipart-encoded.
BaseForm#addPrefix(fieldName)
Returns:the given field name with a prefix added, if this Form has a prefix.
BaseForm#addInitialPrefix(fieldName)

Adds an initial prefix for checking dynamic initial values.

BoundField

class BoundField(form, field, name)

A field and its associated data.

This is the primary means of generating components such as labels and input fields in the default form rendering methods.

Its attributes and methods will be of particular use when implementing custom form layout and rndering.

Arguments:
  • form (Form) – a form.
  • field (Field) – one of the form’s fields.
  • name (String) – the name the field is given by the form.

Instance Attributes

boundField.form

The form this BoundField wraps a field from.

Type:Form
boundField.field

The field this BoundField wraps.

Type:Field
boundField.name

The name associated with the field in the form.

Type:String
boundField.htmlName

A version of the field’s name including any prefix the form has been configured with.

Assuming your forms are configured with prefixes when needed, this should be a unique identifier for any particular field (e.g. if you need something to pass as a key prop to a React component).

Type:String
boundField.label

The label the field is configured with, or a label automatically generated from the field’s name.

Type:String
boundField.helpText

Help text the field is configured with, othewise an empty string.

Type:String

Prototype Functions

BoundField#errors()
Returns:validation errors for the field - if there were none, an empty error list object will be returned.
Type:ErrorList() (by default, but configurable via BaseForm() kwargs.errorConstructor)
BoundField#errorMessage()

Convenience method for getting the first error message for the field, as a single error message is the most common error scenario for a field.

Returns:the first validation error message for the field - if there were none, returns undefined.
BoundField#errorMessages()
Returns:all validation error messages for the field - if there were none, returns an empty list.
BoundField#isHidden()
Returns:true if the field is configured with a hidden widget.
BoundField#autoId()

Calculates and returns the id attribute for this BoundField if the associated form has an autoId set, or set to true. Returns an empty string otherwise.

BoundField#data()
Returns:Raw input data for the field or null if it wasn’t given.
BoundField#idForLabel()

Wrapper around the field widget’s Widget#idForLabel(). Useful, for example, for focusing on this field regardless of whether it has a single widget or a MutiWidget().

BoundField#render([kwargs])

Default rendering method - if the field has showHiddenInitial set, renders the default widget and a hidden version, otherwise just renders the default widget for the field.

Arguments:
BoundField#asWidget([kwargs])

Renders a widget for the field.

Arguments:
  • kwargs (Object) – widget options, which are as follows:
  • kwargs.widget (Widget) – an override for the widget used to render the field - if not provided, the field’s configured widget will be used.
  • kwargs.attrs (Object) – additional HTML attributes to be added to the field’s widget.
BoundField#subWidgets()
Returns:a list of SubWidget() objects that comprise all widgets in this BoundField. This really is only useful for RadioSelect() and CheckboxSelectMultiple() widgets, so that you can iterate over individual inputs when rendering.
BoundField#asText([kwargs])

Renders the field as a text input.

Arguments:
  • kwargs (Object) – widget options, which are as follows:
  • kwargs.attrs (Object) – additional HTML attributes to be added to the field’s widget.
BoundField#asTextarea([kwargs])

Renders the field as a textarea.

Arguments:
  • kwargs (Object) – widget options, which are as follows:
  • kwargs.attrs (Object) – additional HTML attributes to be added to the field’s widget.
BoundField#asHidden([kwargs])

Renders the field as a hidden field.

Arguments:
  • kwargs (Object) – widget options, which are as follows
  • kwargs.attrs (Object) – additional HTML attributes to be added to the field’s widget.
BoundField#value()

Returns the raw value to display for this BoundField, using data if the form is bound, or the initial value otherwise

BoundField#labelTag([kwargs])

Creates a <label> for the field if it has an id attribute, otherwise generates a text label.

Arguments:
  • kwargs (Object) – label customisation options, which are as follows:
  • kwargs.contents (String) – custom contents for the label – if not provided, label contents will be generated from the field itself.
  • kwargs.attrs (Object) – additional HTML attributes to be added to the label tag.
  • kwargs.labelSuffix (String) – a custom suffix for the label.
BoundField#cssClasses([extraClasses])

Returns a string of space-separated CSS classes to be applied to the field.

Arguments:
  • extraClasses (String) – additional CSS classes to be applied to the field