Skip to content

Rendering an element depending on another attribute value

Code speaks more than a thousand words, so here is an example of how to conditionally remove a field if a given country is selected.

<?php

namespace Hyva\Example\Model\FormModifier;

use Hyva\Checkout\Model\Form\EntityFormInterface;
use Hyva\Checkout\Model\Form\EntityFormModifierInterface;

class MyCustomFieldFormModifier implements EntityFormModifierInterface
{
    public function apply(EntityFormInterface $form): EntityFormInterface
    {
        $form->registerModificationListener(
            'init-my-form-field',
            'form:build',
            [$this, 'initMyFormField']
        );

        return $form;
    }

    public function initMyFormField(EntityFormInterface $form)
    {
        $country = $form->getField('country_id')->getValue();
        $myField = $form->getField('my_field');
        if ($country === 'DE' && $myField) {
            $form->removeField($myField);
        }
    }
}

It is also possible to add a field conditionally.
For example:

$myField = $form->createField('my_field', 'text');
$myField->addData(['label' => 'Foo']);

$form->addField($myField);
$form->getField('country_id')->assignRelative($myField);

Here is an example of a select field:

$mySelect = $form->createField('my_select', 'select');
$mySelect->addData([
    'label' => 'Bar',
    'required' => 1,
    'options' => ['' => 'Please Choose', '0' => 'No',  '1' => 'Yes']
]);

Please note that the value of dynamically added fields will not be saved on the entity out-of-the-box. The persistence of such values needs to be implemented on a case by case basis.