class EntityDisplayModeFormBase
Same name in other branches
- 9 core/modules/field_ui/src/Form/EntityDisplayModeFormBase.php \Drupal\field_ui\Form\EntityDisplayModeFormBase
- 8.9.x core/modules/field_ui/src/Form/EntityDisplayModeFormBase.php \Drupal\field_ui\Form\EntityDisplayModeFormBase
- 11.x core/modules/field_ui/src/Form/EntityDisplayModeFormBase.php \Drupal\field_ui\Form\EntityDisplayModeFormBase
Provides the generic base class for entity display mode forms.
Hierarchy
- class \Drupal\Core\Form\FormBase implements \Drupal\Core\Form\FormInterface, \Drupal\Core\DependencyInjection\ContainerInjectionInterface uses \Drupal\Core\DependencyInjection\DependencySerializationTrait, \Drupal\Core\Logger\LoggerChannelTrait, \Drupal\Core\Messenger\MessengerTrait, \Drupal\Core\Routing\RedirectDestinationTrait, \Drupal\Core\StringTranslation\StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm extends \Drupal\Core\Form\FormBase implements \Drupal\Core\Entity\EntityFormInterface
- class \Drupal\field_ui\Form\EntityDisplayModeFormBase extends \Drupal\Core\Entity\EntityForm
- class \Drupal\Core\Entity\EntityForm extends \Drupal\Core\Form\FormBase implements \Drupal\Core\Entity\EntityFormInterface
Expanded class hierarchy of EntityDisplayModeFormBase
File
-
core/
modules/ field_ui/ src/ Form/ EntityDisplayModeFormBase.php, line 18
Namespace
Drupal\field_ui\FormView source
abstract class EntityDisplayModeFormBase extends EntityForm {
/**
* The entity type definition.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* The display context. Either 'view' or 'form'.
*
* @var string
*/
protected string $displayContext;
/**
* The entity type for which the display mode is being created or edited.
*
* @var string|null
*/
protected ?string $targetEntityTypeId;
/**
* {@inheritdoc}
*/
protected function init(FormStateInterface $form_state) {
parent::init($form_state);
$this->entityType = $this->entityTypeManager
->getDefinition($this->entity
->getEntityTypeId());
$this->displayContext = str_replace([
'entity_',
'_mode',
], '', $this->entityType
->id());
}
/**
* Constructs a EntityDisplayModeFormBase object.
*
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entityTypeBundleInfo
* The entity type bundle service.
* @param \Drupal\Core\Entity\EntityDisplayRepository $entityDisplayRepository
* The entity display repository.
*/
public function __construct(EntityTypeBundleInfoInterface $entityTypeBundleInfo, EntityDisplayRepositoryInterface $entityDisplayRepository) {
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('entity_type.bundle.info'), $container->get('entity_display.repository'));
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $entity_type_id = NULL) {
if (!$entity_type_id && !$this->entity
->isNew()) {
$entity_type_id = $this->entity
->getTargetType();
}
$this->targetEntityTypeId = $entity_type_id;
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Name'),
'#maxlength' => 100,
'#default_value' => $this->entity
->label(),
'#required' => TRUE,
];
$form['description'] = [
'#title' => $this->t('Description'),
'#type' => 'textarea',
'#default_value' => $this->entity
->getDescription(),
'#description' => $this->t('This text will be displayed on the @mode_label list page.', [
'@mode_label' => $this->entity
->getEntityType()
->getPluralLabel(),
]),
];
$form['id'] = [
'#type' => 'machine_name',
'#description' => $this->t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
'#disabled' => !$this->entity
->isNew(),
'#default_value' => $this->entity
->id(),
'#field_prefix' => $this->entity
->isNew() ? $this->entity
->getTargetType() . '.' : '',
'#machine_name' => [
'exists' => [
$this,
'exists',
],
'replace_pattern' => '[^a-z0-9_.]+',
],
];
$bundle_info_service = $this->entityTypeBundleInfo;
$bundles = $bundle_info_service->getAllBundleInfo();
$definition = $this->entityTypeManager
->getDefinition($this->entity
->isNew() ? $this->targetEntityTypeId : $this->entity
->getTargetType());
$bundles_by_entity = [];
$defaults = [];
foreach (array_keys($bundles[$definition->id()]) as $bundle) {
$bundles_by_entity[$bundle] = $bundles[$definition->id()][$bundle]['label'];
// Determine default display modes.
if (!$this->entity
->isNew()) {
[
,
$display_mode_name,
] = explode('.', $this->entity
->id());
if ($this->getDisplayByContext($bundle, $display_mode_name)) {
$defaults[$bundle] = $bundle;
}
}
}
$form['bundles_by_entity'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Enable this @display-mode for the following @bundle-label types:', [
'@display-mode' => $this->entityType
->getSingularLabel(),
'@bundle-label' => $definition->getLabel(),
]),
'#description' => $this->t('This @display-mode will still be available for the rest of the @bundle-label types if not checked here, but it will not be enabled by default.', [
'@bundle-label' => $definition->getLabel(),
'@display-mode' => $this->entityType
->getSingularLabel(),
]),
'#options' => $bundles_by_entity,
'#default_value' => $defaults,
];
return $form;
}
/**
* Determines if the display mode already exists.
*
* @param string|int $entity_id
* The entity ID.
* @param array $element
* The form element.
*
* @return bool
* TRUE if the display mode exists, FALSE otherwise.
*/
public function exists($entity_id, array $element) {
// Do not allow to add internal 'default' view mode.
if ($entity_id == 'default') {
return TRUE;
}
/** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $storage */
$storage = $this->entityTypeManager
->getStorage($this->entity
->getEntityTypeId());
return (bool) $storage->getQuery()
->condition('id', $element['#field_prefix'] . $entity_id)
->execute();
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$this->messenger()
->addStatus($this->t('Saved the %label @entity-type.', [
'%label' => $this->entity
->label(),
'@entity-type' => $this->entityType
->getSingularLabel(),
]));
$this->entity
->save();
\Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
$form_state->setRedirectUrl($this->entity
->toUrl('collection'));
[
,
$display_mode_name,
] = explode('.', $form_state->getValue('id'));
$target_entity_id = $this->targetEntityTypeId;
foreach ($form_state->getValue('bundles_by_entity') as $bundle => $value) {
if (!empty($value)) {
// Add a new entity view/form display if it doesn't already exist.
if (!$this->getDisplayByContext($bundle, $display_mode_name)) {
$display = $this->getEntityDisplay($target_entity_id, $bundle, 'default')
->createCopy($display_mode_name);
$display->save();
}
// This message is still helpful, even if the view/form display hasn't
// changed, so we keep it outside the above check.
$url = $this->getOverviewUrl($display_mode_name, $value);
$bundle_info_service = $this->entityTypeBundleInfo;
$bundles = $bundle_info_service->getAllBundleInfo();
$bundle_label = $bundles[$target_entity_id][$bundle]['label'];
$display_mode_label = $form_state->getValue('label');
$this->messenger()
->addStatus($this->t('<a href=":url">Configure the %display_mode_label %mode mode for %bundle_label</a>.', [
'%mode' => $this->displayContext,
'%display_mode_label' => $display_mode_label,
'%bundle_label' => $bundle_label,
':url' => $url->toString(),
]));
}
else {
// The view/form display has been unchecked, so we need to delete this.
// There's no confirmation of deleting the view/form display on the node
// content type forms either, so we match that behavior.
if ($display = $this->getDisplayByContext($bundle, $display_mode_name)) {
$display->delete();
}
}
}
}
/**
* Returns an entity display object to be used by this form.
*
* @param string $entity_type_id
* The target entity type ID of the entity display.
* @param string $bundle
* The target bundle of the entity display.
* @param string $mode
* A view or form mode.
*
* @return \Drupal\Core\Entity\Display\EntityDisplayInterface
* An entity display.
*/
private function getEntityDisplay($entity_type_id, $bundle, $mode) {
return match ($this->displayContext) { 'view' => $this->entityDisplayRepository
->getViewDisplay($entity_type_id, $bundle, $mode),
'form' => $this->entityDisplayRepository
->getFormDisplay($entity_type_id, $bundle, $mode),
};
}
/**
* Returns the Url object for a specific entity (form) display edit form.
*
* @param string $mode
* The form or view mode.
* @param string $bundle
* The entity bundle name.
*
* @return \Drupal\Core\Url
* A Url object for the overview route.
*/
private function getOverviewUrl($mode, $bundle) : Url {
$entity_type = $this->entityTypeManager
->getDefinition($this->targetEntityTypeId);
return match ($this->displayContext) { 'view' => Url::fromRoute('entity.entity_view_display.' . $this->targetEntityTypeId . '.view_mode', [
'view_mode_name' => $mode,
] + FieldUI::getRouteBundleParameter($entity_type, $bundle)),
'form' => Url::fromRoute('entity.entity_form_display.' . $this->targetEntityTypeId . '.form_mode', [
'form_mode_name' => $mode,
] + FieldUI::getRouteBundleParameter($entity_type, $bundle)),
};
}
/**
* Load the view display for a given bundle and view mode name.
*
* @param string $bundle
* The entity bundle to load the view display for.
* @param string $view_mode_name
* The view mode name such as "full_content" to load the view display for.
*
* @return \Drupal\Core\Entity\Display\EntityViewDisplayInterface|null
* Returns the view display, or NULL if one does not exist.
*/
private function getViewDisplay(string $bundle, string $view_mode_name) : ?EntityViewDisplayInterface {
$view_mode_id = $this->targetEntityTypeId . '.' . $bundle . '.' . $view_mode_name;
return $this->entityTypeManager
->getStorage('entity_view_display')
->load($view_mode_id);
}
/**
* Load the form display for a given bundle and form mode name.
*
* @param string $bundle
* The entity bundle to load the form display for.
* @param string $form_mode_name
* The form mode name to load the form display for.
*
* @return \Drupal\Core\Entity\Display\EntityFormDisplayInterface|null
* Returns the form display, or NULL if one does not exist.
*/
private function getFormDisplay(string $bundle, string $form_mode_name) : ?EntityFormDisplayInterface {
$form_mode_id = $this->targetEntityTypeId . '.' . $bundle . '.' . $form_mode_name;
return $this->entityTypeManager
->getStorage('entity_form_display')
->load($form_mode_id);
}
/**
* Returns View or Form display based on display context.
*
* @param string $bundle
* The entity bundle to load the display for.
* @param string $display_mode_name
* The display mode name to load the display for.
*
* @return \Drupal\Core\Entity\Display\EntityFormDisplayInterface|\Drupal\Core\Entity\Display\EntityViewDisplayInterface|null
* Returns the display, or NULL if one does not exist.
*/
private function getDisplayByContext(string $bundle, string $display_mode_name) : EntityFormDisplayInterface|EntityViewDisplayInterface|null {
return match ($this->displayContext) { 'view' => $this->getViewDisplay($bundle, $display_mode_name),
'form' => $this->getFormDisplay($bundle, $display_mode_name),
};
}
}
Members
Title Sort descending | Modifiers | Object type | Summary | Overriden Title | Overrides |
---|---|---|---|---|---|
DependencySerializationTrait::$_entityStorages | protected | property | |||
DependencySerializationTrait::$_serviceIds | protected | property | |||
DependencySerializationTrait::__sleep | public | function | 1 | ||
DependencySerializationTrait::__wakeup | public | function | 2 | ||
EntityDisplayModeFormBase::$displayContext | protected | property | The display context. Either 'view' or 'form'. | ||
EntityDisplayModeFormBase::$entityType | protected | property | The entity type definition. | ||
EntityDisplayModeFormBase::$targetEntityTypeId | protected | property | The entity type for which the display mode is being created or edited. | ||
EntityDisplayModeFormBase::buildForm | public | function | Form constructor. | Overrides EntityForm::buildForm | 1 |
EntityDisplayModeFormBase::create | public static | function | Instantiates a new instance of this class. | Overrides FormBase::create | |
EntityDisplayModeFormBase::exists | public | function | Determines if the display mode already exists. | ||
EntityDisplayModeFormBase::form | public | function | Gets the actual form array to be built. | Overrides EntityForm::form | |
EntityDisplayModeFormBase::getDisplayByContext | private | function | Returns View or Form display based on display context. | ||
EntityDisplayModeFormBase::getEntityDisplay | private | function | Returns an entity display object to be used by this form. | ||
EntityDisplayModeFormBase::getFormDisplay | private | function | Load the form display for a given bundle and form mode name. | ||
EntityDisplayModeFormBase::getOverviewUrl | private | function | Returns the Url object for a specific entity (form) display edit form. | ||
EntityDisplayModeFormBase::getViewDisplay | private | function | Load the view display for a given bundle and view mode name. | ||
EntityDisplayModeFormBase::init | protected | function | Initialize the form state and the entity before the first form build. | Overrides EntityForm::init | |
EntityDisplayModeFormBase::save | public | function | Form submission handler for the 'save' action. | Overrides EntityForm::save | |
EntityDisplayModeFormBase::__construct | public | function | Constructs a EntityDisplayModeFormBase object. | ||
EntityForm::$entity | protected | property | The entity being used by this form. | 11 | |
EntityForm::$entityTypeManager | protected | property | The entity type manager. | 3 | |
EntityForm::$moduleHandler | protected | property | The module handler service. | 2 | |
EntityForm::$operation | protected | property | The name of the current operation. | ||
EntityForm::actions | protected | function | Returns an array of supported actions for the current entity form. | 36 | |
EntityForm::actionsElement | protected | function | Returns the action form element for the current entity form. | ||
EntityForm::afterBuild | public | function | Form element #after_build callback: Updates the entity with submitted data. | 1 | |
EntityForm::buildEntity | public | function | Builds an updated entity object based upon the submitted form values. | Overrides EntityFormInterface::buildEntity | 5 |
EntityForm::copyFormValuesToEntity | protected | function | Copies top-level form values to entity properties. | 11 | |
EntityForm::getBaseFormId | public | function | Returns a string identifying the base form. | Overrides BaseFormIdInterface::getBaseFormId | 4 |
EntityForm::getEntity | public | function | Gets the form entity. | Overrides EntityFormInterface::getEntity | |
EntityForm::getEntityFromRouteMatch | public | function | Determines which entity will be used by this form from a RouteMatch object. | Overrides EntityFormInterface::getEntityFromRouteMatch | 3 |
EntityForm::getFormId | public | function | Returns a unique string identifying the form. | Overrides FormInterface::getFormId | 13 |
EntityForm::getOperation | public | function | Gets the operation identifying the form. | Overrides EntityFormInterface::getOperation | |
EntityForm::prepareEntity | protected | function | Prepares the entity object before the form is built first. | 3 | |
EntityForm::prepareInvokeAll | protected | function | Invokes the specified prepare hook variant. | ||
EntityForm::processForm | public | function | Process callback: assigns weights and hides extra fields. | ||
EntityForm::setEntity | public | function | Sets the form entity. | Overrides EntityFormInterface::setEntity | |
EntityForm::setEntityTypeManager | public | function | Sets the entity type manager for this form. | Overrides EntityFormInterface::setEntityTypeManager | |
EntityForm::setModuleHandler | public | function | Sets the module handler for this form. | Overrides EntityFormInterface::setModuleHandler | |
EntityForm::setOperation | public | function | Sets the operation for this form. | Overrides EntityFormInterface::setOperation | |
EntityForm::submitForm | public | function | This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form stateā¦ |
Overrides FormInterface::submitForm | 20 |
FormBase::$configFactory | protected | property | The config factory. | 3 | |
FormBase::$requestStack | protected | property | The request stack. | 1 | |
FormBase::$routeMatch | protected | property | The route match. | ||
FormBase::config | protected | function | Retrieves a configuration object. | ||
FormBase::configFactory | protected | function | Gets the config factory for this form. | 3 | |
FormBase::container | private | function | Returns the service container. | ||
FormBase::currentUser | protected | function | Gets the current user. | 2 | |
FormBase::getRequest | protected | function | Gets the request object. | ||
FormBase::getRouteMatch | protected | function | Gets the route match. | ||
FormBase::logger | protected | function | Gets the logger for a specific channel. | ||
FormBase::redirect | protected | function | Returns a redirect response object for the specified route. | ||
FormBase::resetConfigFactory | public | function | Resets the configuration factory. | ||
FormBase::setConfigFactory | public | function | Sets the config factory for this form. | ||
FormBase::setRequestStack | public | function | Sets the request stack object to use. | ||
FormBase::validateForm | public | function | Form validation handler. | Overrides FormInterface::validateForm | 57 |
LoggerChannelTrait::$loggerFactory | protected | property | The logger channel factory service. | ||
LoggerChannelTrait::getLogger | protected | function | Gets the logger for a specific channel. | ||
LoggerChannelTrait::setLoggerFactory | public | function | Injects the logger channel factory. | ||
MessengerTrait::$messenger | protected | property | The messenger. | 16 | |
MessengerTrait::messenger | public | function | Gets the messenger. | 16 | |
MessengerTrait::setMessenger | public | function | Sets the messenger. | ||
RedirectDestinationTrait::$redirectDestination | protected | property | The redirect destination service. | 2 | |
RedirectDestinationTrait::getDestinationArray | protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | ||
RedirectDestinationTrait::getRedirectDestination | protected | function | Returns the redirect destination service. | ||
RedirectDestinationTrait::setRedirectDestination | public | function | Sets the redirect destination service. | ||
StringTranslationTrait::$stringTranslation | protected | property | The string translation service. | 3 | |
StringTranslationTrait::formatPlural | protected | function | Formats a string containing a count of items. | ||
StringTranslationTrait::getNumberOfPlurals | protected | function | Returns the number of plurals supported by a given language. | ||
StringTranslationTrait::getStringTranslation | protected | function | Gets the string translation service. | ||
StringTranslationTrait::setStringTranslation | public | function | Sets the string translation service to use. | 2 | |
StringTranslationTrait::t | protected | function | Translates a string to the current language or to a given language. |
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.