Nested FormsΒΆ

Formular does not just support flat forms as introduced in Creating, Validating And Rendering A Form. You can also use nesting or accept an arbitary number of values.

Let’s assume we have a simple web application to organize the students for a school. We want to allow the user to add one student with a simple form but we also want to create a table-like interface to add an arbitary number of students. At the client side we can use Javascript to simply add more fields as required but how do we validate this?

First let’s create a simple form for a single student:

class Student(Form):
    forename = TextField(label=u"Forename", required=True)
    surename = TextField(label=u"Surename", required=True)
    birth = DateField(label=u"Date of birth", required=True)

Under the hood a formular.forms.Form is just a wrapper around a formular.fields.Mapping which is in fact a field. So to validate the data of multiple students we just have to pass this mapping to a formular.fields.Multiple:

class MultipleStudents(Form):
    students = Multiple(Student.as_mapping())

The MultipleStudentsForm takes an arbitary number of students, although you can limit the number by using validators. You could render this form to a table in which each row represents a student.

If you want to add/remove fields with Javascript you should know how the names for the fields are created. The name of the text input which takes the forename for the first student is students.0.forename, for the second student it’s students.1.forename and so on. However Formular isn’t strict here, those names could also be students.23.forename and students.42.forename, Formular just cares about the order of the integers.

Previous topic

Creating, Validating And Rendering A Form

Next topic

Writing Extensions

This Page