class NodeTypeForm

Same name in other branches
  1. 9 core/modules/node/src/NodeTypeForm.php \Drupal\node\NodeTypeForm
  2. 8.9.x core/modules/node/src/NodeTypeForm.php \Drupal\node\NodeTypeForm
  3. 11.x core/modules/node/src/NodeTypeForm.php \Drupal\node\NodeTypeForm

Form handler for node type forms.

@internal

Hierarchy

Expanded class hierarchy of NodeTypeForm

File

core/modules/node/src/NodeTypeForm.php, line 17

Namespace

Drupal\node
View source
class NodeTypeForm extends BundleEntityFormBase {
    
    /**
     * The entity field manager.
     *
     * @var \Drupal\Core\Entity\EntityFieldManagerInterface
     */
    protected $entityFieldManager;
    
    /**
     * Constructs the NodeTypeForm object.
     *
     * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
     *   The entity field manager.
     */
    public function __construct(EntityFieldManagerInterface $entity_field_manager) {
        $this->entityFieldManager = $entity_field_manager;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('entity_field.manager'));
    }
    
    /**
     * {@inheritdoc}
     */
    public function form(array $form, FormStateInterface $form_state) {
        $form = parent::form($form, $form_state);
        $type = $this->entity;
        if ($this->operation == 'add') {
            $form['#title'] = $this->t('Add content type');
            $fields = $this->entityFieldManager
                ->getBaseFieldDefinitions('node');
            // Create a node with a fake bundle using the type's UUID so that we can
            // get the default values for workflow settings.
            // @todo Make it possible to get default values without an entity.
            //   https://www.drupal.org/node/2318187
            $node = $this->entityTypeManager
                ->getStorage('node')
                ->create([
                'type' => $type->uuid(),
            ]);
        }
        else {
            $form['#title'] = $this->t('Edit %label content type', [
                '%label' => $type->label(),
            ]);
            $fields = $this->entityFieldManager
                ->getFieldDefinitions('node', $type->id());
            // Create a node to get the current values for workflow settings fields.
            $node = $this->entityTypeManager
                ->getStorage('node')
                ->create([
                'type' => $type->id(),
            ]);
        }
        $form['name'] = [
            '#title' => $this->t('Name'),
            '#type' => 'textfield',
            '#default_value' => $type->label(),
            '#description' => $this->t('The human-readable name for this content type, displayed on the <em>Content types</em> page.'),
            '#required' => TRUE,
            '#size' => 30,
        ];
        $form['type'] = [
            '#type' => 'machine_name',
            '#default_value' => $type->id(),
            '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
            '#disabled' => $type->isLocked(),
            '#machine_name' => [
                'exists' => [
                    'Drupal\\node\\Entity\\NodeType',
                    'load',
                ],
                'source' => [
                    'name',
                ],
            ],
            '#description' => $this->t('Unique machine-readable name: lowercase letters, numbers, and underscores only.', [
                '%node-add' => $this->t('Add content'),
            ]),
        ];
        $form['description'] = [
            '#title' => $this->t('Description'),
            '#type' => 'textarea',
            '#default_value' => $type->getDescription(),
            '#description' => $this->t('Displays on the <em>Content types</em> page.'),
        ];
        $form['additional_settings'] = [
            '#type' => 'vertical_tabs',
            '#attached' => [
                'library' => [
                    'node/drupal.content_types',
                ],
            ],
        ];
        $form['submission'] = [
            '#type' => 'details',
            '#title' => $this->t('Submission form settings'),
            '#group' => 'additional_settings',
            '#open' => TRUE,
        ];
        $form['submission']['title_label'] = [
            '#title' => $this->t('Title field label'),
            '#type' => 'textfield',
            '#default_value' => $fields['title']->getLabel(),
            '#required' => TRUE,
        ];
        $form['submission']['preview_mode'] = [
            '#type' => 'radios',
            '#title' => $this->t('Preview before submitting'),
            '#default_value' => $type->getPreviewMode(),
            '#options' => [
                DRUPAL_DISABLED => $this->t('Disabled'),
                DRUPAL_OPTIONAL => $this->t('Optional'),
                DRUPAL_REQUIRED => $this->t('Required'),
            ],
        ];
        $form['submission']['help'] = [
            '#type' => 'textarea',
            '#title' => $this->t('Explanation or submission guidelines'),
            '#default_value' => $type->getHelp(),
            '#description' => $this->t('This text will be displayed at the top of the page when creating or editing content of this type.'),
        ];
        $form['workflow'] = [
            '#type' => 'details',
            '#title' => $this->t('Publishing options'),
            '#group' => 'additional_settings',
        ];
        $workflow_options = [
            'status' => $node->status->value,
            'promote' => $node->promote->value,
            'sticky' => $node->sticky->value,
            'revision' => $type->shouldCreateNewRevision(),
        ];
        // Prepare workflow options to be used for 'checkboxes' form element.
        $keys = array_keys(array_filter($workflow_options));
        $workflow_options = array_combine($keys, $keys);
        $form['workflow']['options'] = [
            '#type' => 'checkboxes',
            '#title' => $this->t('Default options'),
            '#default_value' => $workflow_options,
            '#options' => [
                'status' => $this->t('Published'),
                'promote' => $this->t('Promoted to front page'),
                'sticky' => $this->t('Sticky at top of lists'),
                'revision' => $this->t('Create new revision'),
            ],
            '#description' => $this->t('Users with sufficient access rights will be able to override these options.'),
        ];
        if ($this->moduleHandler
            ->moduleExists('language')) {
            $form['language'] = [
                '#type' => 'details',
                '#title' => $this->t('Language settings'),
                '#group' => 'additional_settings',
            ];
            $language_configuration = ContentLanguageSettings::loadByEntityTypeBundle('node', $type->id());
            $form['language']['language_configuration'] = [
                '#type' => 'language_configuration',
                '#entity_information' => [
                    'entity_type' => 'node',
                    'bundle' => $type->id(),
                ],
                '#default_value' => $language_configuration,
            ];
        }
        $form['display'] = [
            '#type' => 'details',
            '#title' => $this->t('Display settings'),
            '#group' => 'additional_settings',
        ];
        $form['display']['display_submitted'] = [
            '#type' => 'checkbox',
            '#title' => $this->t('Display author and date information'),
            '#default_value' => $type->displaySubmitted(),
            '#description' => $this->t('Author username and publish date will be displayed.'),
        ];
        return $this->protectBundleIdElement($form);
    }
    
    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        parent::validateForm($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 buildEntity(array $form, FormStateInterface $form_state) {
        
        /** @var \Drupal\node\NodeTypeInterface $entity */
        $entity = parent::buildEntity($form, $form_state);
        // The description and help text cannot be empty strings.
        if (trim($form_state->getValue('description')) === '') {
            $entity->set('description', NULL);
        }
        if (trim($form_state->getValue('help')) === '') {
            $entity->set('help', NULL);
        }
        return $entity;
    }
    
    /**
     * {@inheritdoc}
     */
    public function save(array $form, FormStateInterface $form_state) {
        $type = $this->entity;
        $type->setNewRevision($form_state->getValue([
            'options',
            'revision',
        ]));
        $type->set('type', trim($type->id()));
        $type->set('name', trim($type->label()));
        $status = $type->save();
        $t_args = [
            '%name' => $type->label(),
        ];
        if ($status == SAVED_UPDATED) {
            $this->messenger()
                ->addStatus($this->t('The content type %name has been updated.', $t_args));
        }
        elseif ($status == SAVED_NEW) {
            node_add_body_field($type);
            $this->messenger()
                ->addStatus($this->t('The content type %name has been added.', $t_args));
            $context = array_merge($t_args, [
                'link' => $type->toLink($this->t('View'), 'collection')
                    ->toString(),
            ]);
            $this->logger('node')
                ->notice('Added content type %name.', $context);
        }
        $fields = $this->entityFieldManager
            ->getFieldDefinitions('node', $type->id());
        // Update title field definition.
        $title_field = $fields['title'];
        $title_label = $form_state->getValue('title_label');
        if ($title_field->getLabel() != $title_label) {
            $title_field->getConfig($type->id())
                ->setLabel($title_label)
                ->save();
        }
        // Update workflow options.
        // @todo Make it possible to get default values without an entity.
        //   https://www.drupal.org/node/2318187
        $node = $this->entityTypeManager
            ->getStorage('node')
            ->create([
            'type' => $type->id(),
        ]);
        foreach ([
            'status',
            'promote',
            'sticky',
        ] as $field_name) {
            $value = (bool) $form_state->getValue([
                'options',
                $field_name,
            ]);
            if ($node->{$field_name}->value != $value) {
                $fields[$field_name]->getConfig($type->id())
                    ->setDefaultValue($value)
                    ->save();
            }
        }
        $this->entityFieldManager
            ->clearCachedFieldDefinitions();
        $form_state->setRedirectUrl($type->toUrl('collection'));
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
BundleEntityFormBase::protectBundleIdElement protected function Protects the bundle entity&#039;s ID property&#039;s form element against changes.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
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::buildForm public function Form constructor. Overrides FormInterface::buildForm 13
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::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::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.
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.
NodeTypeForm::$entityFieldManager protected property The entity field manager.
NodeTypeForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityForm::buildEntity
NodeTypeForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
NodeTypeForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
NodeTypeForm::save public function Form submission handler for the &#039;save&#039; action. Overrides EntityForm::save
NodeTypeForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
NodeTypeForm::__construct public function Constructs the NodeTypeForm object.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; 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.