Skip to content

Related form Elements

Form elements can "belong together".
For example, the street of an address can consist of several fields.

This kind of field relationship is declared in Hyvä Checkout by setting an element as the relative of another element.

Using the street example, the additional street fields are relatives of the primary street field.

The primary field is considered the "Ancestor" of the related fields.

If element B is a relative of element A, then element A is considered the Ancestor of element B, and element B will be rendered below element A.

Both form elements and fields can be "related".

The value of related fields is represented as an array on the magewire component, where each field value is a record in the array.

For form elements that are not fields, the relationship only influences where the related element is rendered.

Element relationships are manipulated using the methods assignRelative and removeRelative.

For example:

// $formElementA and $formElementB are both EntityFormElementInterface instances

$formElementA->assignRelative($formElementB)
How exactly related elements are rendered depends on the ancestor. By default, related elements are rendered below the ancestor.

Elements can be nested on more than one level.
The number of ancestors an element has can be determined by calling $element->getLevel().

Ancestor values

Assigning a field as a relative to a parent, will change the ancestors value type to an array.
The ancestors' field value will be the first array item, followed by each related fields' value as the subsequent records.

Example: address street fields

Think of the address street fields. Depending on the system configuration, the street consists of between one and four fields. The first street input field is the ancestor, while the second, third and fourth are related fields.

If the street is a single field, the magewire component address.street property will be a string.
If it consists of two or more fields, it will be an array.

To get a list of all elements assigned as a relative, $element->getRelatives() can be used.

To remove an element from its ancestor, the method $ancestor->removeRelative($relatedElement) is available.

Avoid changing relations in form:build:magewire!

Do not change the element hierarchy in form:build:magewire hook callbacks.
When the form:build:magewire hook methods are called, the form structure has already been finalized.

Changing the element hierarchy at this point in time will cause unwanted effects, such as fields being rendered twice.

Avoid assignAncestor and removeAncestor

Form elements ancestors can be manipulated directly using the methods assignAncestor(EntityFormElementInterface $ancestor) and removeAncestor().
However, this can cause the form field hierarchy to become inconsistent.

It is safer to use assignRelative and removeRelative, as they ensure the consistency of all the related properties.