New Drupal module: multi-value form elements
In this short article I want to introduce you to a new module we recently released on Drupal.org, namely Multi-value form element.
This small module provides a form element that allows you to easily define multi-value elements in your custom forms. Much like what field widgets provide with the Add another item Ajax button.
So how does it work? Easy, really. All you have to do is define a form element of the '#type' => 'multivalue'
with one or more children, defined like you normally would. So for example:
$form['names'] = [
'#type' => 'multivalue',
'#title' => $this->t('Names'),
'name' => [
'#type' => 'textfield',
'#title' => $this->t('Name'),
],
];
Would give you this:
And you can also use multiple form element children if you want:
$form['contacts'] = [
'#type' => 'multivalue',
'#title' => $this->t('Contacts'),
'name' => [
'#type' => 'textfield',
'#title' => $this->t('Name'),
],
'mail' => [
'#type' => 'email',
'#title' => $this->t('E-mail'),
],
];
So as you can see, no big deal to use. But all the complex Ajax logic of adding extra values is out of your hands now and can easily build nice forms.
Check out some more examples of how to use this element and what options it has above the Drupal\multivalue_form_element\Element\MultiValue
class.
This module is sponsored by the European Commission as part of the OpenEuropa initiative and all the work my colleagues and myself are doing there.