Form.withSectionsCollection - Andrei15193/react-model-view-viewmodel GitHub Wiki
API / Form<TValidationError> / withSectionsCollection method
Adds the provided sections collection to the form, this is similar to the Form.withSections
method,
the difference being that a custom collection can be added for better handling the addition and removal
of sections as well as keeping a clean interface.
Any changes made to the returned collection is reflected in the form as well, added sections are added, removed sections are removed, sorting or moving sections around are moved in the form as well.
protected withSectionsCollection(
sectionsCollection: IReadOnlyFormCollection<Form<TValidationError>, TValidationError>
): IReadOnlyFormCollection<Form<TValidationError>, TValidationError>
Source reference: src/forms/Form.ts:842
.
-
sectionsCollection: IReadOnlyFormCollection<Form<TValidationError>, TValidationError>
The sections collection to add.
Returns: IReadOnlyFormCollection<Form<TValidationError>, TValidationError>
Returns the provided sections collection.
One usecase for sections is to split the form up and group fields together to make it easier to understand and maintain.
The other usecase is for more complex forms where there are lists of items that themselves are editable, but also the list itself, items can be added or removed. Things like a todo list, or tables with a number of fields.
For full control on how items are added to the collection, extend from ReadOnlyFormCollection<TForm, TValidationError>
, this
requires that methods for adding and removing items need to be defined, all standard mutating methods are available
as protected from the base class.
class ToDoList extends Form {
public constructor() {
super();
this.withFields(
this.name = new FormField({
name: 'name',
initialValue: ''
})
)
this.withSectionsCollection(
this.items = new ToDoItemsCollection()
);
}
public readonly name: FormField<string>;
public readonly items: ToDoItemsCollection
}
class ToDoItemsCollection extends ReadOnlyFormCollection<ToDoItem> {
public add(): ToDoItem {
const item = new ToDoItem();
this.push(item);
return item;
}
public remove(item: ToDoItem): void {
const itemIndex = this.indexOf(item);
if (itemIndex >= 0)
this.splice(itemIndex, 1);
}
}
class ToDoItem extends Form {
public constructor() {
super();
this.withFields(
this.description = new FormField({
name: 'name',
initialValue: ''
})
);
}
public readonly description: FormField<string>;
}