### Install and Require newforms
Source: https://newforms.readthedocs.io/en/latest/index.html
Installation via npm and basic module requirement for Node.js environments.
```bash
npm install newforms
```
```javascript
var forms = require('newforms')
```
--------------------------------
### Render RenderFormSet component
Source: https://newforms.readthedocs.io/en/latest/react_components.html
Examples of initializing RenderFormSet using either a Form constructor or a FormSet constructor.
```jsx
```
--------------------------------
### Dynamic Choices with ProjectBookingForm
Source: https://newforms.readthedocs.io/en/latest/fields.html
Example of creating a form with dynamic choices for projects using a custom form constructor and the `makeChoices` helper.
```APIDOC
## Dynamic choices
A common pattern for providing dynamic choices (or indeed, dynamic anything) is to provide your own form constructor and pass in whatever data is required to make changes to `form.fields` as the form is being instantiated.
Newforms provides a `util.makeChoices()` helper function for creating choice pairs from a list of objects using named properties:
```javascript
var ProjectBookingForm = forms.Form.extend({
project: forms.ChoiceField(),
hours: forms.DecimalField({minValue: 0, maxValue: 24, maxdigits: 4, decimalPlaces: 2}),
date: forms.DateField(),
constructor: function(projects, kwargs) {
// Call the constructor of whichever form you're extending so that the
// forms.Form constructor eventually gets called - this.fields doesn't
// exist until this happens.
forms.Form.call(this, kwargs)
// Now that this.fields is a thing, make whatever changes you need to -
// in this case, we're going to creata a list of pairs of project ids
// and names to set as the project field's choices.
this.fields.project.setChoices(forms.util.makeChoices(projects, 'id', 'name'))
}
})
var projects = [
{id: 1, name: 'Project 1'}
, {id: 2, name: 'Project 2'}
, {id: 3, name: 'Project 3'}
]
var form = new ProjectBookingForm(projects, {autoId: false})
print(reactHTML((form.boundField('project').render()))
/* =>
*/
```
Server-side example of using a form with dynamic choices:
```javascript
// Users are assigned to projects and they're booking time, so we need to:
// 1. Display choices for the projects they're assigned to
// 2. Validate that the submitted project id is one they've been assigned to
var form
var display = function() { res.render('book_time', {form: form}) }
req.user.getProjects(function(err, projects) {
if (err) { return next(err) }
if (req.method == 'POST') {
form = new ProjectBookingForm(projects, {data: req.body})
if (form.isValid()) {
return ProjectService.saveHours(user, form.cleanedData, function(err) {
if (err) { return next(err) }
return res.redirect('/time/book/')
})
}
}
else {
form = new ProjectBookingForm(projects)
}
display(form)
})
```
```
--------------------------------
### Define a Signup Form with Fields and Custom Validation
Source: https://newforms.readthedocs.io/en/latest/react_client.html
This example shows how to define a form with email, password, and terms fields, including a custom 'clean' method for cross-field validation.
```javascript
var SignupForm = forms.Form.extend({
email: forms.EmailField(),
password: forms.CharField({widget: forms.PasswordInput}),
confirm: forms.CharField({label: 'Confirm password', widget: forms.PasswordInput}),
terms: forms.BooleanField({
label: 'I have read and agree to the Terms and Conditions',
errorMessages: {required: 'You must accept the terms to continue'}
}),
clean: function() {
if (this.cleanedData.password && this.cleanedData.confirm &&
this.cleanedData.password != this.cleanedData.confirm) {
throw forms.ValidationError('Passwords do not match.')
}
}
})
```
--------------------------------
### GenericIPAddressField() IPv6 Normalization Example
Source: https://newforms.readthedocs.io/en/latest/fields.html
Demonstrates IPv6 address normalization according to RFC 4291, including IPv4-mapped addresses. All characters are converted to lowercase.
```python
from django.forms import GenericIPAddressField
ip_field = GenericIPAddressField()
# Example of IPv6 normalization
print(ip_field.normalize('2001:0::0:01'))
# Output: 2001::1
# Example of IPv4-mapped address normalization
print(ip_field.normalize('::ffff:0a0a:0a0a'))
# Output: ::ffff:10.10.10.10
```
--------------------------------
### Define ChoiceField choices
Source: https://newforms.readthedocs.io/en/latest/fields_api.html
Example of the structure for the choices argument in a ChoiceField.
```javascript
{choices: [[1, 'One'], [2, 'Two']]}
```
--------------------------------
### Define choice pairs
Source: https://newforms.readthedocs.io/en/latest/fields.html
Example of defining a list of choice pairs for a Select widget.
```javascript
var STATE_CHOICES = [
['S', 'Scoped']
, ['D', 'Defined']
, ['P', 'In-Progress']
, ['C', 'Completed']
, ['A', 'Accepted']
]
print(reactHTML(forms.Select().render('state', null, {choices: STATE_CHOICES})))
```
--------------------------------
### Define grouped choice lists
Source: https://newforms.readthedocs.io/en/latest/fields.html
Example of using optgroups to categorize choices within a Select widget.
```javascript
var DRINK_CHOICES = [
['Cheap', [
[1, 'White Lightning']
, [2, 'Buckfast']
, [3, 'Tesco Gin']
]
]
, ['Expensive', [
[4, 'Vieille Bon Secours Ale']
, [5, 'Château d’Yquem']
, [6, 'Armand de Brignac Midas']
]
]
, [7, 'Beer']
]
print(reactHTML(forms.Select().render('drink', null, {choices: DRINK_CHOICES})))
```
--------------------------------
### Extend MultiWidget to Create DateSelectorWidget
Source: https://newforms.readthedocs.io/en/latest/widgets.html
This example demonstrates how to extend MultiWidget to create a custom widget for selecting dates. It includes implementations for the constructor, decompress, formatOutput, and valueFromData methods.
```javascript
var DateSelectorWidget = forms.MultiWidget.extend({
constructor: function(kwargs) {
kwargs = extend({attrs: {}}, kwargs)
widgets = [
forms.Select({choices: range(1, 32), attrs: kwargs.attrs}),
forms.Select({choices: range(1, 13), attrs: kwargs.attrs}),
forms.Select({choices: range(2012, 2017), attrs: kwargs.attrs})
]
forms.MultiWidget.call(this, widgets, kwargs)
},
decompress: function(value) {
if (value instanceof Date) {
return [value.getDate(),
value.getMonth() + 1, // Make month 1-based for display
value.getFullYear()]
}
return [null, null, null]
},
formatOutput: function(renderedWidgets) {
return React.createElement('div', null, renderedWidgets)
},
valueFromData: function(data, files, name) {
var parts = this.widgets.map(function(widget, i) {
return widget.valueFromData(data, files, name + '_' + i)
})
parts.reverse() // [d, m, y] => [y, m, d]
return parts.join('-')
}
})
```
--------------------------------
### EmailField Validation Example
Source: https://newforms.readthedocs.io/en/latest/fields.html
Demonstrates how to use the clean() method of an EmailField for validation. Shows successful validation and how to catch validation errors.
```javascript
var f = forms.EmailField()
print(f.clean('foo@example.com'))
// => foo@example.com
try {
f.clean('invalid email address')
}
catch (e) {
print(e.messages())
}
// => ["Enter a valid email address."]
```
--------------------------------
### Optional CharField Example
Source: https://newforms.readthedocs.io/en/latest/fields.html
Shows how to create a CharField that is not required by passing `required: false` to the constructor. An empty value will return a normalized empty string instead of raising a ValidationError.
```javascript
var f = forms.CharField({required: false})
```
--------------------------------
### Customize RenderForm containers
Source: https://newforms.readthedocs.io/en/latest/react_components.html
Example of using component, className, and rowComponent props to customize the HTML structure of a rendered form.
```jsx
```
--------------------------------
### Declarative Fields Meta Setup
Source: https://newforms.readthedocs.io/en/latest/forms_api.html
Use `DeclarativeFieldsMeta()` as a mixin to set up form fields during Form constructor creation. It handles field inheritance and precedence from prototype properties, mixins, and base classes.
```javascript
DeclarativeFieldsMeta(_prototypeProps_)
```
--------------------------------
### Define a Form and Render with Prefixes
Source: https://newforms.readthedocs.io/en/latest/react_components.html
Define a form class and use the prefix prop to manage multiple instances of the same form.
```javascript
var ParentForm = forms.Form.extend({
name: forms.CharField(),
dob: forms.DateField({label: 'Date of birth'})
})
```
```javascript
```
--------------------------------
### Get BoundFields as a List
Source: https://newforms.readthedocs.io/en/latest/custom_display.html
Use `form.boundFields()` to get a list of all BoundField instances for a form, ordered as defined in the form. This is useful for iterating through fields in their declared order.
```python
form.boundFields()
```
--------------------------------
### Get Validation Errors for a Field
Source: https://newforms.readthedocs.io/en/latest/custom_display.html
Use `bf.errors()` to get an object containing validation error messages for a BoundField. It includes a default rendering to a `
`.
```python
bf.errors()
```
--------------------------------
### Get Field Validation Status
Source: https://newforms.readthedocs.io/en/latest/custom_display.html
Use `bf.status()` to get the current validation status of a field as a string. Possible values are 'pending', 'error', 'valid', or 'default'. This method is available from version 0.10.
```python
bf.status()
```
--------------------------------
### Form Constructor
Source: https://newforms.readthedocs.io/en/latest/forms_api.html
Initializes a new Form instance with specific configuration options for data binding, validation, and rendering behavior.
```APIDOC
## Form Constructor
### Description
Initializes a collection of Fields that knows how to validate and display itself.
### Parameters
- **kwargs.data** (Object) - Optional - Input form data for binding.
- **kwargs.files** (Object) - Optional - Input file data.
- **kwargs.errors** (ErrorObject) - Optional - Initial errors to be displayed.
- **kwargs.validation** (String/Object) - Optional - Configures form-wide interactive validation.
- **kwargs.controlled** (Boolean) - Optional - Configures whether the form renders controlled components.
- **kwargs.onChange** (Function) - Optional - Callback function triggered on input data or validation state changes.
- **kwargs.autoId** (String) - Optional - Template for generating field id attributes.
- **kwargs.prefix** (String) - Optional - Prefix applied to the name of each field.
- **kwargs.initial** (Object) - Optional - Initial form data for rendering.
- **kwargs.errorConstructor** (Function) - Optional - Constructor for creating error details.
- **kwargs.labelSuffix** (String) - Optional - Suffix used when generating labels.
- **kwargs.emptyPermitted** (Boolean) - Optional - Whether the form is allowed to be empty.
```
--------------------------------
### Instantiate a Form with Data
Source: https://newforms.readthedocs.io/en/latest/forms.html
Initialize a form with a data object containing field values.
```javascript
var data = {
subject: 'hello'
, message: 'Hi there'
, sender: 'foo@example.com'
, ccMyself: true
}
var f = new ContactForm({data: data})
```
--------------------------------
### Extend TextInput constructor
Source: https://newforms.readthedocs.io/en/latest/fields.html
Shows how to create a custom widget constructor by extending TextInput.
```javascript
var TelInput = TextInput.extend({
inputType: 'tel'
})
```
--------------------------------
### Retrieve raw field value
Source: https://newforms.readthedocs.io/en/latest/forms.html
Use boundField.value() to get the raw value of a field as it would be rendered by a widget.
```javascript
var initial = {subject: 'welcome'}
var data = {subject: 'hi'}
var unboundForm = new ContactForm({initial: initial})
var boundForm = new ContactForm({data: data, initial: initial})
print(unboundForm.boundField('subject').value())
// => welcome
print(boundForm.boundField('subject').value())
// => hi
```
--------------------------------
### Instantiate a Form
Source: https://newforms.readthedocs.io/en/latest/forms.html
Create a new instance of a form without initial data.
```javascript
var f = new ContactForm()
```
--------------------------------
### Get field ID for label
Source: https://newforms.readthedocs.io/en/latest/forms.html
Use idForLabel() to retrieve the ID of a field, useful for manual JSX label construction.
```javascript