function FieldStorageReuseForm::reuseCallback
Same name in other branches
- 10 core/modules/field_ui/src/Form/FieldStorageReuseForm.php \Drupal\field_ui\Form\FieldStorageReuseForm::reuseCallback()
Callback function to handle re-using an existing field.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Throws
\Exception Thrown when there is an error re-using the field.
File
-
core/
modules/ field_ui/ src/ Form/ FieldStorageReuseForm.php, line 244
Class
- FieldStorageReuseForm
- Provides a form for the "field storage" add page.
Namespace
Drupal\field_ui\FormCode
public function reuseCallback(array $form, FormStateInterface $form_state) {
$entity_type = $this->entityTypeManager
->getDefinition($this->entityTypeId);
$field_name = $form_state->getTriggeringElement()['#name'];
// Get settings from existing configuration.
$default_options = $this->getExistingFieldDefaults($field_name);
$fields = $this->entityTypeManager
->getStorage('field_config')
->getQuery()
->accessCheck()
->condition('entity_type', $this->entityTypeId)
->condition('field_name', $field_name)
->execute();
$field = $fields ? $this->entityTypeManager
->getStorage('field_config')
->load(reset($fields)) : NULL;
// Have a default label in case a field storage doesn't have any fields.
$existing_storage_label = $field ? $field->label() : $field_name;
try {
$field = $this->entityTypeManager
->getStorage('field_config')
->create([
$default_options['field_config'] ?? [],
'field_name' => $field_name,
'entity_type' => $this->entityTypeId,
'bundle' => $this->bundle,
'label' => $existing_storage_label,
// Field translatability should be explicitly enabled by the users.
'translatable' => FALSE,
]);
$field->save();
// Configure the display modes.
$this->configureEntityFormDisplay($field_name, $default_options['entity_form_display'] ?? []);
$this->configureEntityViewDisplay($field_name, $default_options['entity_view_display'] ?? []);
// Store new field information for any additional submit handlers.
$form_state->set([
'fields_added',
'_add_existing_field',
], $field_name);
$form_state->setRedirect("entity.field_config.{$this->entityTypeId}_field_edit_form", array_merge(FieldUI::getRouteBundleParameter($entity_type, $this->bundle), [
'field_config' => "{$this->entityTypeId}.{$this->bundle}.{$field_name}",
]));
} catch (\Exception $e) {
$this->messenger()
->addError($this->t('There was a problem reusing field %label: @message', [
'%label' => $existing_storage_label,
'@message' => $e->getMessage(),
]));
}
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.