Problem/Motivation

MultiValue::setDefaultValue() only walks the direct children of a row, so a child that is itself a container never passes default values down to its own children. The method carried a @todo saying as much.

Proposed resolution

Recursively get child default values.

Remaining tasks

Review.

User interface changes

None.

API changes

None. Default values for nested children mirror the structure the form returns, which is what callers already receive on submit.


Original Report

Problem/Motivation

Drupal\multivalue_form_element\Element\MultiValue::setDefaultValue does not support nested elements, eg. a container element with other elements inside.

Steps to reproduce

Example form structure:

$form['custom'] = [
    '#type' => 'multivalue',
    '#title' => 'Custom sources',
    '#description' => 'A space-separated list of additional sources to allow.',
    '#default_value' => array_map(
        static function (array $source) { return ['container' => $source]; },
        $this->service->getSources($directive)
    ),
];
$form['custom']['container'] = [
    '#type' => 'container',
    '#attributes' => ['class' => ['form-items-inline']],
    '#tree' => false,
];
$form['custom']['container']['source'] = [
    '#type' => 'textfield',
    '#title' => 'Source to allow',
    '#size' => 50,
];
$form['custom']['container']['comment'] = [
    '#type' => 'textfield',
    '#title' => 'Comment',
    '#size' => 50,
];
Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

DieterHolvoet created an issue. See original summary.

dieterholvoet’s picture

Status: Active » Needs review
sardara’s picture

I need to look into this, I left a comment in the code for two possible reasons, one is that simply I didn't had time to do it or that there was an issue somewhere :) I'll try to check asap.

lincolnh0’s picture

StatusFileSize
new907 bytes

I have mocked up a simple patch that seems to be working for me. This does however require the nesting element (presumably something like details, fieldset, fieldgroup to set the #tree variable to TRUE

dieterholvoet’s picture

I already opened a merge request with proposed changes 8 months ago, please apply any necessary changes there.

atropoides’s picture

Version: 1.0.x-dev » 1.0.0-beta5
Status: Needs review » Reviewed & tested by the community

Tested with version 1.0.0-beta5. Worked great for me, thanks for the solution.

adinancenci’s picture

StatusFileSize
new593 bytes

So, patch #5 have fixed some occurrences in one of our sites but in other forms it had the exact opposite effect, causing the bug to occur where once it was working just fine.

I tweaked patch #5, it worked for us. ( tested with 1.0.0-beta4 ).

adinancenci’s picture

adinancenci’s picture

Damn... can someone please rename the patch above to reflect the comment ?

psf_’s picture

#9 tested with version 1.0.0-beta6. Work for me.

In buildForm() I have:

$form['legal_links'] = [
      '#type' => 'multivalue',
      '#title' => $this->t('Legal links'),
      '#description' => $this->t('Links to legal documents in the enrollment form. Leave empty a row to remove it.'),
      '#cardinality' => MultiValue::CARDINALITY_UNLIMITED,
      '#default_value' => $links,
      'link_title' => [
        '#type' => 'textfield',
        '#title' => $this->t('Title'),
        '#description' => $this->t('To include a link, please provide a title as well.'),
      ],
      'link' => [
        '#type' => 'textfield',
        '#title' => $this->t('Link'),
        '#maxlength' => 2048,
        '#element_validate' => [[static::class, 'validateUriElement']],
        '#link_type' => LinkItemInterface::LINK_GENERIC,
        '#description' => $this->t(
          'You can enter an internal path such as %add-node or an external URL such as %url. Enter %front to link to the front page. Enter %nolink to display link text only. Enter %button to display keyboard-accessible link text only.',
          [
            '%front' => '<front>',
            '%add-node' => '/node/add',
            '%url' => 'http://example.com',
            '%nolink' => '<nolink>',
            '%button' => '<button>',
          ]
        ),
      ],
    ];

And to save, in submitForm():

$this->config('mymodule.settings')
      ->set('legal_links', $form_state->getValue('legal_links'))
      ->save();
sardara’s picture

Status: Reviewed & tested by the community » Needs work
Issue tags: +Needs tests

Test coverage has to be added.
Off the top of my head, I think I didn't add support for nested elements because of the possibility of having #tree set to true or false, making it hard to handle complex cases. Please test that scenario when adding tests.

monymirza’s picture

Status: Needs work » Needs review
Related issues: +#3232914: text_format elements are not supported
StatusFileSize
new1.01 KB

text_format elements added along this.

darvanen’s picture

Status: Needs review » Needs work

Setting to NW as maintainer has asked for tests.

darvanen’s picture

Version: 1.0.0-beta5 » 2.0.x-dev
Assigned: Unassigned » darvanen
Issue summary: View changes

darvanen’s picture

Assigned: darvanen » Unassigned
Status: Needs work » Needs review

New MR against 2.0.x, with tests. Writing the tests turned up something that changes what the fix should be, so it's worth spelling out.

The earlier patches here treated two situations as different: a container child that sets #tree to TRUE, and one that says nothing about it. Inside a multivalue row those are the same situation. The element switches #tree on for itself, and Drupal hands that setting down to everything inside it, so a container's fields end up grouped under the container's own name either way. Switching #tree off for a container doesn't give you ungrouped fields either. It lifts that container's values out of the element completely, up to the top of the form, where each row overwrites the one before it.

So the MR does one thing: when a child has fields of its own, it hands that child the part of the saved data kept under the child's name, and repeats that for anything nested deeper. A child that switches #tree off is skipped, because its values are no longer part of the element.

The tests cover the two cases the issue asked for, which turn out to be one case: a container that says nothing about #tree, and one that sets it to TRUE. Both fill their fields from saved values when the form is built, and both return the same structure when it's submitted.

darvanen’s picture

Issue tags: -Needs tests
darvanen’s picture

Parent issue: » #3608015: [meta] Version 2.x
bceyssens’s picture

Status: Needs review » Reviewed & tested by the community

Switched from #8 to MR !26 on our site (1.0.0-beta8, applies cleanly there too). We have a multivalue with a details > details > checkbox structure inside each row and the defaults are filled correctly on all levels.

Code and tests look good to me, the is_array check also fixes a TypeError #8 had when a container got a scalar value. RTBC for us.

@sardara any chance this can also land on 1.0.x, or is 2.0.x getting a release soon?