Profile picture for user admin
Daniel Sipos
30 Nov 2020

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:

drupal multi value form elements example

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.

Profile picture for user admin

Daniel Sipos

CEO @ Web Omelette

Danny founded WEBOMELETTE in 2012 as a passion project, mostly writing about Drupal problems he faced day to day, as well as about new technologies and things that he thought other developers would find useful. Now he now manages a team of developers and designers, delivering quality products that make businesses successful.

Contact us

Comments

Rolando 28 May 2021 16:41

Thank you very much for this…

Thank you very much for this module. It is really very useful.

Brian 26 Jun 2021 00:47

Thanks for contributing this…

Thanks for contributing this. I previously did this manually for a custom need by copying some of the great work in the Webform module which does something similar.

Add new comment