You are here

class EckEntityBundleForm in Entity Construction Kit (ECK) 8

Form controller for ECK entity bundle forms.

Hierarchy

Expanded class hierarchy of EckEntityBundleForm

File

src/Form/EntityBundle/EckEntityBundleForm.php, line 19

Namespace

Drupal\eck\Form\EntityBundle
View source
class EckEntityBundleForm extends EntityForm {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFieldManager = $entity_field_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    $entity_type_id = $this->entity
      ->getEntityType()
      ->getBundleOf();
    $type = $this->entity;
    $entity = $this->entityTypeManager
      ->getStorage($entity_type_id)
      ->create([
      'type' => $this->operation == 'add' ? $type
        ->uuid() : $type
        ->id(),
    ]);
    $type_label = $entity
      ->getEntityType()
      ->getLabel();
    $form['name'] = [
      '#title' => $this
        ->t('Name'),
      '#type' => 'textfield',
      '#default_value' => $type->name,
      '#description' => $this
        ->t('The human-readable name of this entity bundle. This text will be displayed as part of the list on the <em>Add @type content</em> page. This name must be unique.', [
        '@type' => $type_label,
      ]),
      '#required' => TRUE,
      '#size' => 30,
    ];
    $form['type'] = [
      '#type' => 'machine_name',
      '#default_value' => $type
        ->id(),
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
      '#disabled' => $type
        ->isLocked(),
      '#machine_name' => [
        'exists' => [
          $this,
          'exists',
        ],
        'source' => [
          'name',
        ],
      ],
      '#description' => $this
        ->t('A unique machine-readable name for this entity type bundle. It must only contain lowercase letters, numbers, and underscores. This name will be used for constructing the URL of the Add %type content page, in which underscores will be converted into hyphens.', [
        '%type' => $type_label,
      ]),
    ];
    $form['description'] = [
      '#title' => $this
        ->t('Description'),
      '#type' => 'textarea',
      '#default_value' => $type->description,
      '#description' => $this
        ->t('Describe this entity type bundle. The text will be displayed on the <em>Add @type content</em> page.', [
        '@type' => $type_label,
      ]),
    ];

    // Field title overrides.
    $entity_type_config = \Drupal::config('eck.eck_entity_type.' . $entity_type_id);
    $base_fields = $this->entityFieldManager
      ->getBaseFieldDefinitions($type
      ->getEntityType()
      ->getBundleOf());
    $bundle_overrides = [];
    if ($type
      ->id() !== NULL) {
      $bundle_overrides = $this->entityFieldManager
        ->getFieldDefinitions($entity_type_id, $type
        ->id());
    }
    foreach ([
      'title',
      'uid',
      'created',
      'changed',
      'status',
    ] as $field) {
      if (!empty($entity_type_config
        ->get($field))) {
        if (!isset($form['field_overrides'])) {
          $form['field_overrides'] = [
            '#type' => 'details',
            '#title' => $this
              ->t('Base field title and description overrides'),
            '#open' => FALSE,
          ];
        }
        $form['field_overrides'][$field] = [
          '#type' => 'fieldset',
          '#title' => $base_fields[$field]
            ->getLabel(),
          '#tree' => FALSE,
        ];
        $fieldset =& $form['field_overrides'][$field];
        if (isset($bundle_overrides[$field])) {
          $title_override = $bundle_overrides[$field]
            ->getLabel();
          if ($title_override === $base_fields[$field]
            ->getLabel()) {
            unset($title_override);
          }
        }
        $fieldset[$field . '_title_override'] = [
          '#type' => 'textfield',
          '#title' => $this
            ->t('Title'),
          '#description' => $this
            ->t('New title for the base @title field.', [
            '@title' => $field,
          ]),
          '#default_value' => $title_override ?? '',
        ];
        if (isset($bundle_overrides[$field])) {
          $description_override = $bundle_overrides[$field]
            ->getDescription();
          if ($description_override === $base_fields[$field]
            ->getDescription()) {
            unset($description_override);
          }
        }
        $fieldset[$field . '_description_override'] = [
          '#type' => 'textfield',
          '#title' => $this
            ->t('Description'),
          '#description' => $this
            ->t('New description for the base @title field. Enter %none to hide the default description.', [
            '@title' => $field,
            '%none' => '<none>',
          ]),
          '#default_value' => $description_override ?? '',
        ];
      }
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this
      ->t('Save bundle');
    $actions['delete']['#value'] = $this
      ->t('Delete bundle');
    return $actions;
  }

  /**
   * {@inheritdoc}
   */
  public function validate(array $form, FormStateInterface $form_state) {
    parent::validate($form, $form_state);
    $id = trim($form_state
      ->getValue('type'));

    // '0' is invalid, since elsewhere we check it using empty().
    if ($id == '0') {
      $form_state
        ->setErrorByName('type', $this
        ->t("Invalid machine-readable name. Enter a name other than %invalid.", [
        '%invalid' => $id,
      ]));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $type = $this->entity;
    $type->type = trim($type
      ->id());
    $type->name = trim($type->name);
    $status = $type
      ->save();
    $t_args = [
      '%name' => $type
        ->label(),
    ];
    if ($status == SAVED_UPDATED) {
      \Drupal::messenger()
        ->addMessage($this
        ->t('The entity bundle %name has been updated.', $t_args));
    }
    elseif ($status == SAVED_NEW) {
      \Drupal::messenger()
        ->addMessage($this
        ->t('The entity bundle %name has been added.', $t_args));
      $context = array_merge($t_args, [
        'link' => Link::fromTextAndUrl($this
          ->t('View'), new Url('eck.entity.' . $type
          ->getEntityType()
          ->getBundleOf() . '_type.list'))
          ->toString(),
      ]);
      $this
        ->logger($this->entity
        ->getEntityTypeId())
        ->notice('Added entity bundle %name.', $context);
    }

    // Update field labels definition.
    $bundle_fields = $this->entityFieldManager
      ->getFieldDefinitions($type
      ->getEntityType()
      ->getBundleOf(), $type
      ->id());
    $base_fields = $this->entityFieldManager
      ->getBaseFieldDefinitions($type
      ->getEntityType()
      ->getBundleOf());
    foreach ([
      'created',
      'changed',
      'uid',
      'title',
      'status',
    ] as $field) {
      if (!$form_state
        ->hasValue($field . '_title_override')) {
        continue;
      }
      $has_changed = FALSE;
      $field_definition = $bundle_fields[$field];
      $field_config = $field_definition
        ->getConfig($type
        ->id());
      $label = $form_state
        ->getValue($field . '_title_override') ?: $base_fields[$field]
        ->getLabel();
      if ($field_definition
        ->getLabel() != $label) {
        $field_config
          ->setLabel($label);
        $has_changed = TRUE;
      }
      $description = $form_state
        ->getValue($field . '_description_override') ?: $base_fields[$field]
        ->getDescription();
      if ($field_definition
        ->getDescription() != $description) {
        $field_config
          ->setDescription($description);
        $has_changed = TRUE;
      }
      if ($has_changed) {
        $field_config
          ->save();
      }
    }
    $this->entityFieldManager
      ->clearCachedFieldDefinitions();
    $form_state
      ->setRedirect('eck.entity.' . $type
      ->getEntityType()
      ->getBundleOf() . '_type.list');
  }

  /**
   * Checks for an existing ECK bundle.
   *
   * @param string $type
   *   The bundle type.
   * @param array $element
   *   The form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return bool
   *   TRUE if this bundle already exists in the entity type, FALSE otherwise.
   */
  public function exists($type, array $element, FormStateInterface $form_state) {
    $bundleStorage = \Drupal::entityTypeManager()
      ->getStorage($this->entity
      ->getEckEntityTypeMachineName() . '_type');
    return (bool) $bundleStorage
      ->load($type);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EckEntityBundleForm::$entityFieldManager protected property The entity field manager.
EckEntityBundleForm::$entityTypeManager protected property The entity type manager. Overrides EntityForm::$entityTypeManager
EckEntityBundleForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
EckEntityBundleForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
EckEntityBundleForm::exists public function Checks for an existing ECK bundle.
EckEntityBundleForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
EckEntityBundleForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
EckEntityBundleForm::validate public function
EckEntityBundleForm::__construct public function The constructor.
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
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.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
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 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
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::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
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 17
EntityForm::__get public function
EntityForm::__set public function
FormBase::$configFactory protected property The config factory. 1
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. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
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. Overrides UrlGeneratorTrait::redirect
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 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.