I want to add fields depending on the first option selected. I also made a form with a similar behaviour but it wasn't a field widget.
I used this module as an example to make the form
I'm not sure if the way I implement this AJAX behavior should be different in a widget.
Can the behavior of this form be implemented in a field widget? I'm trying to look for examples of specifically field widgets implementing this but I still haven't found anything that could help `
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$value = isset($items[$delta]->value) ? $items[$delta]->value : '';
$element = [];
// Gather the number of names in the form already.
$num_names = $form_state->get('num_names');
// We have to ensure that there is at least one name field.
if ($num_names === NULL) {
$name_field = $form_state->set('num_names', 1);
$num_names = 1;
}
$element['breakpoints'] = [
'#type' => 'select',
'#title' => $this->t('Breakpoint group'),
'#options' => $this->getBreakpointsGroups(),
'#default_value' => $value,
'#empty_option' => $this->t('-Select a breakpoint group-'),
];
$element['images_fieldset'] = [
'#type' => 'fieldset',
'#title' => $this->t('Load images for each breakpoint'),
'#prefix' => '<div id="breakpoint-wrapper">',
'#suffix' => '</div>',
];
for ($i = 0; $i < $num_names; $i++) {
$element['images_fieldset']['image'][$i] = [
'#type' => 'image',
'#title' => $this->t('Image'),
'#name' => "Name"
];
}
$element['images_fieldset']['submit'] = [
'#type' => 'submit',
'#title' => 'Submit',
'#submit' => ['::submitForm'],
'#value' => $this->t("submit"),
'#ajax' => [
'callback' => '::loadImageFields',
'wrapper' => 'breakpoint-wrapper',
],
];
return ['value' => $element];
}
/**
* Returns a list of breakpoints.
*
* @return array
* An associative array of breakpoints, suitable to use as form
* options.
*/
protected function getBreakpointsGroups() {
$breakpoints = \Drupal::service('breakpoint.manager')->getGroups();
$breakpoint_names = array_keys($breakpoints);
$breakpoint_group = array();
foreach ($breakpoint_names as $name) {
$breakpoint_group += [$name => $name];
}
return $breakpoint_group;
}
protected function submitForm($form, &$form_state) {
$state = $form_state->getTriggeringElement();
$breakpoint= $state['#value'];
$array = array();
$breakpoint = \Drupal::service('breakpoint.manager')->getBreakpointsByGroup($breakpoint);
$breakpoints_name = array_keys($breakpoint);
foreach ($breakpoints_name as $breakpoint_definition) {
$mediaQuery = $breakpoint[$breakpoint_definition]->getMediaQuery();
array_push($array,$mediaQuery);
}
$name_field = $form_state->get('num_names');
$form_state->set('num_names',count($array));
$form_state->setRebuild();
}
public function loadImageFields(array $form, FormStateInterface $form_state) {
return $form['images_fieldset'];
}
}