Utilities

Newforms exposes various utilities you may want to make use of when working with forms, as well as some implementation details which you may need to make use of for customisation purposes.

formData(form)

Creates an object representation of a form’s elements’ contents.

Arguments:
  • form

    a form DOM node or a String specifying a form’s id or name attribute.

    If a String is given, id is tried before name when attempting to find the form in the DOM. An error will be thrown if the form can’t be found.

Returns:

an object representing the data present in the form, with input names as properties. Inputs with multiple values or duplicate names will have a list of values set.

validateAll(form, formsAndFormsets)

Extracts data from a <form> using formData() and validates it with a list of Forms and/or FormSets.

Arguments:
  • form – the <form> into which any given forms and formsets have been rendered – this can be a React <form> component or a real <form> DOM node.
  • formsAndFormsets (Array) – a list of Form and/or FormSet instances to be used to validate the <form>‘s input data.
Returns:

true if the <form>‘s input data are valid according to all given forms and formsets

util.formatToArray(str, obj[, options])

Replaces '{placeholders}' in a string with same-named properties from a given Object, but interpolates into and returns an Array instead of a String.

By default, any resulting empty strings are stripped out of the Array before it is returned. To disable this, pass an options object with a 'strip' property which is false.

This is useful for simple templating which needs to include ReactElement objects.

Arguments:
  • str (String) – a String containing placeholder names surrounded by { }
  • obj (Object) – an Object whose properties will provide replacements for placeholders
  • options (Object) – an options Object which can be used to disable stripping of empty strings from the resulting Array before it is returned by passing {strip: false}
util.makeChoices(list, submitValueProp, displayValueProp)

Creates a list of [submitValue, displayValue] choice pairs from a list of objects.

If any of the property names correspond to a function in an object, the function will be called with the object as the this context.

Arguments:
  • list (Array) – a list of objects
  • submitValueProp (String) – the name of the property in each object holding the value to be submitted/returned when it’s a selected choice.
  • displayValueProp (String) – the name of the property in each object holding the value to be displayed for selection by the user.