public static function MediaLibrary::removeItem in Media Library Form API Element 8
Same name and namespace in other branches
- 2.x src/Element/MediaLibrary.php \Drupal\media_library_form_element\Element\MediaLibrary::removeItem()
Submit callback for remove buttons.
Parameters
array $form: The form array.
\Drupal\Core\Form\FormStateInterface $form_state: The form state.
Return value
mixed The updated form element.
File
- src/
Element/ MediaLibrary.php, line 476
Class
- MediaLibrary
- Provides a Media library form element.
Namespace
Drupal\media_library_form_element\ElementCode
public static function removeItem(array &$form, FormStateInterface $form_state) {
$triggering_element = $form_state
->getTriggeringElement();
// Get the parents required to find the top-level widget element.
if (count($triggering_element['#array_parents']) < 4) {
throw new \LogicException('Expected the remove button to be more than four levels deep in the form. Triggering element parents were: ' . implode(',', $triggering_element['#array_parents']));
}
$parents = array_slice($triggering_element['#array_parents'], 0, -4);
$element = NestedArray::getValue($form, $parents);
$user_input_parents = array_slice($triggering_element['#parents'], 0, -4);
$delta = array_slice($triggering_element['#array_parents'], -3, 1)[0];
if (isset($element['selection'][$delta])) {
unset($element['selection'][$delta]);
$items = array_filter($element['selection'], static function ($k) {
return is_numeric($k);
}, ARRAY_FILTER_USE_KEY);
$remaining_items = [];
foreach ($items as $item) {
/** @var \Drupal\media\Entity\Media $media_item */
$media_item = $item['preview']['rendered_entity']['#media'];
if ($media_item instanceof Media) {
$remaining_items[] = $media_item
->id();
}
}
$selection = implode(',', $remaining_items);
// Remove our value.
$element['media_library_selection']['#value'] = $selection;
$element['media_library_selection']['#default_value'] = $selection;
$element['#value'] = $selection;
$element['#default_value'] = $selection;
// Clear the formstate values.
$form_state
->setValueForElement($element, $selection);
// Clear formstate user input.
$user_input = $form_state
->getUserInput();
NestedArray::setValue($user_input, $user_input_parents, $selection);
$form_state
->setUserInput($user_input);
$form_state
->setValue($user_input_parents, $selection);
}
// Refresh the form element.
$form_state
->setRebuild();
}