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.