Score:1

How to add an unique wrapper id to a widget element?

lb flag

I made a widget that "generates" fields based on the option chosen of a select field. I got most of the logic done:

1- An option is chosen from this field:

 $element['value'] = [
  '#type' => 'select',
  '#options' => $this->getBreakpointsGroups(),
  '#default_value' => $value,
  '#ajax' => [
    'callback' => [$this,'updateBreakpoint'], // don't forget :: when calling a class method.
    'event' => 'change',
    'wrapper' => $wrapper_id, // This element is updated with this AJAX callback.
    'method' => 'html',
  ]
];  

2-Then the function updateBreakpoint is executed and it proceeds to update the form. First I extract the wrapper value in case there are multiple widget forms so it doesn't target another instance of the same form.

    $state = $form_state->getTriggeringElement();
    $wrapper_id = $state['#ajax']['wrapper'];

3- After making some changes to the form I return the changes and use an AJAX command

    $ajax_response = new AjaxResponse();
    $ajax_response->addCommand(new HtmlCommand("div#{$wrapper_id}",  $form['image_fieldset']));
    return $ajax_response;

The wrapper is defined inside the formElement function in the following way:

    $wrapper_id = Html::getUniqueId('wrapper');

The problem is that no change is made. When I define $wrapper_id as a string without any unique id functions ('wrapper' for example) the changes are made. I'm confused as to why. I made sure to check the value of the wrapper persisted in all the form.

berliner avatar
bd flag
I think it would help to see your full code for the form builder method and the `updateBreakpoint` method.
Score:0
cn flag

If you have multiple wrappers on the same page you can't rely solely on Html::getUniqueId. You need to add as much predictable information as available.

For example in a single field widget element you can add the field name, the field parents and the field delta:

$field_name = $this->fieldDefinition->getName();
$parents = $form['#parents'];
$prefix = implode('-', array_merge($parents, [$field_name, $delta]));

$wrapper_id = $prefix . '-my-wrapper';
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.