NodeTypeForm.php 8.95 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\node;

5
use Drupal\Core\Entity\BundleEntityFormBase;
6
use Drupal\Core\Entity\EntityManagerInterface;
7
use Drupal\Core\Entity\EntityTypeInterface;
8
use Drupal\Core\Form\FormStateInterface;
9
use Drupal\language\Entity\ContentLanguageSettings;
10
use Symfony\Component\DependencyInjection\ContainerInterface;
11 12

/**
13
 * Form handler for node type forms.
14 15
 *
 * @internal
16
 */
17
class NodeTypeForm extends BundleEntityFormBase {
18

19 20 21 22 23 24 25 26 27 28 29
  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * Constructs the NodeTypeForm object.
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
30
   *   The entity manager.
31 32 33 34 35 36 37 38 39 40 41 42 43 44
   */
  public function __construct(EntityManagerInterface $entity_manager) {
    $this->entityManager = $entity_manager;
  }

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

45 46 47
  /**
   * {@inheritdoc}
   */
48
  public function form(array $form, FormStateInterface $form_state) {
49 50 51 52
    $form = parent::form($form, $form_state);

    $type = $this->entity;
    if ($this->operation == 'add') {
53
      $form['#title'] = $this->t('Add content type');
54 55 56 57 58
      $fields = $this->entityManager->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
59
      $node = $this->entityManager->getStorage('node')->create(['type' => $type->uuid()]);
60
    }
61
    else {
62
      $form['#title'] = $this->t('Edit %label content type', ['%label' => $type->label()]);
63 64
      $fields = $this->entityManager->getFieldDefinitions('node', $type->id());
      // Create a node to get the current values for workflow settings fields.
65
      $node = $this->entityManager->getStorage('node')->create(['type' => $type->id()]);
66 67
    }

68
    $form['name'] = [
69 70
      '#title' => t('Name'),
      '#type' => 'textfield',
71
      '#default_value' => $type->label(),
72
      '#description' => t('The human-readable name of this content type. This text will be displayed as part of the list on the <em>Add content</em> page. This name must be unique.'),
73 74
      '#required' => TRUE,
      '#size' => 30,
75
    ];
76

77
    $form['type'] = [
78 79
      '#type' => 'machine_name',
      '#default_value' => $type->id(),
80
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
81
      '#disabled' => $type->isLocked(),
82
      '#machine_name' => [
83
        'exists' => ['Drupal\node\Entity\NodeType', 'load'],
84 85 86
        'source' => ['name'],
      ],
      '#description' => t('A unique machine-readable name for this content type. It must only contain lowercase letters, numbers, and underscores. This name will be used for constructing the URL of the %node-add page, in which underscores will be converted into hyphens.', [
87
        '%node-add' => t('Add content'),
88 89
      ]),
    ];
90

91
    $form['description'] = [
92 93
      '#title' => t('Description'),
      '#type' => 'textarea',
94
      '#default_value' => $type->getDescription(),
95
      '#description' => t('This text will be displayed on the <em>Add new content</em> page.'),
96
    ];
97

98
    $form['additional_settings'] = [
99
      '#type' => 'vertical_tabs',
100 101 102 103
      '#attached' => [
        'library' => ['node/drupal.content_types'],
      ],
    ];
104

105
    $form['submission'] = [
106 107 108
      '#type' => 'details',
      '#title' => t('Submission form settings'),
      '#group' => 'additional_settings',
109
      '#open' => TRUE,
110 111
    ];
    $form['submission']['title_label'] = [
112 113
      '#title' => t('Title field label'),
      '#type' => 'textfield',
114
      '#default_value' => $fields['title']->getLabel(),
115
      '#required' => TRUE,
116 117
    ];
    $form['submission']['preview_mode'] = [
118 119
      '#type' => 'radios',
      '#title' => t('Preview before submitting'),
120
      '#default_value' => $type->getPreviewMode(),
121
      '#options' => [
122 123 124
        DRUPAL_DISABLED => t('Disabled'),
        DRUPAL_OPTIONAL => t('Optional'),
        DRUPAL_REQUIRED => t('Required'),
125 126 127
      ],
    ];
    $form['submission']['help']  = [
128 129
      '#type' => 'textarea',
      '#title' => t('Explanation or submission guidelines'),
130
      '#default_value' => $type->getHelp(),
131
      '#description' => t('This text will be displayed at the top of the page when creating or editing content of this type.'),
132 133
    ];
    $form['workflow'] = [
134 135 136
      '#type' => 'details',
      '#title' => t('Publishing options'),
      '#group' => 'additional_settings',
137 138
    ];
    $workflow_options = [
139 140 141
      'status' => $node->status->value,
      'promote' => $node->promote->value,
      'sticky' => $node->sticky->value,
142
      'revision' => $type->isNewRevision(),
143
    ];
144 145 146
    // Prepare workflow options to be used for 'checkboxes' form element.
    $keys = array_keys(array_filter($workflow_options));
    $workflow_options = array_combine($keys, $keys);
147
    $form['workflow']['options'] = [
148
      '#type' => 'checkboxes',
149
      '#title' => t('Default options'),
150
      '#default_value' => $workflow_options,
151
      '#options' => [
152 153 154 155
        'status' => t('Published'),
        'promote' => t('Promoted to front page'),
        'sticky' => t('Sticky at top of lists'),
        'revision' => t('Create new revision'),
156
      ],
157
      '#description' => t('Users with the <em>Administer content</em> permission will be able to override these options.'),
158
    ];
159
    if ($this->moduleHandler->moduleExists('language')) {
160
      $form['language'] = [
161 162 163
        '#type' => 'details',
        '#title' => t('Language settings'),
        '#group' => 'additional_settings',
164
      ];
165

166
      $language_configuration = ContentLanguageSettings::loadByEntityTypeBundle('node', $type->id());
167
      $form['language']['language_configuration'] = [
168
        '#type' => 'language_configuration',
169
        '#entity_information' => [
170 171
          'entity_type' => 'node',
          'bundle' => $type->id(),
172
        ],
173
        '#default_value' => $language_configuration,
174
      ];
175
    }
176
    $form['display'] = [
177 178 179
      '#type' => 'details',
      '#title' => t('Display settings'),
      '#group' => 'additional_settings',
180 181
    ];
    $form['display']['display_submitted'] = [
182
      '#type' => 'checkbox',
183
      '#title' => t('Display author and date information'),
184
      '#default_value' => $type->displaySubmitted(),
185
      '#description' => t('Author username and publish date will be displayed.'),
186
    ];
187 188

    return $this->protectBundleIdElement($form);
189 190 191 192 193
  }

  /**
   * {@inheritdoc}
   */
194
  protected function actions(array $form, FormStateInterface $form_state) {
195 196 197 198 199 200 201 202 203
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = t('Save content type');
    $actions['delete']['#value'] = t('Delete content type');
    return $actions;
  }

  /**
   * {@inheritdoc}
   */
204 205
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
206

207
    $id = trim($form_state->getValue('type'));
208 209
    // '0' is invalid, since elsewhere we check it using empty().
    if ($id == '0') {
210
      $form_state->setErrorByName('type', $this->t("Invalid machine-readable name. Enter a name other than %invalid.", ['%invalid' => $id]));
211 212 213 214 215 216
    }
  }

  /**
   * {@inheritdoc}
   */
217
  public function save(array $form, FormStateInterface $form_state) {
218
    $type = $this->entity;
219
    $type->setNewRevision($form_state->getValue(['options', 'revision']));
220 221
    $type->set('type', trim($type->id()));
    $type->set('name', trim($type->label()));
222 223 224

    $status = $type->save();

225
    $t_args = ['%name' => $type->label()];
226 227 228 229 230

    if ($status == SAVED_UPDATED) {
      drupal_set_message(t('The content type %name has been updated.', $t_args));
    }
    elseif ($status == SAVED_NEW) {
231
      node_add_body_field($type);
232
      drupal_set_message(t('The content type %name has been added.', $t_args));
233
      $context = array_merge($t_args, ['link' => $type->link($this->t('View'), 'collection')]);
234
      $this->logger('node')->notice('Added content type %name.', $context);
235 236
    }

237 238 239
    $fields = $this->entityManager->getFieldDefinitions('node', $type->id());
    // Update title field definition.
    $title_field = $fields['title'];
240 241 242
    $title_label = $form_state->getValue('title_label');
    if ($title_field->getLabel() != $title_label) {
      $title_field->getConfig($type->id())->setLabel($title_label)->save();
243 244 245 246
    }
    // Update workflow options.
    // @todo Make it possible to get default values without an entity.
    //   https://www.drupal.org/node/2318187
247 248
    $node = $this->entityManager->getStorage('node')->create(['type' => $type->id()]);
    foreach (['status', 'promote', 'sticky'] as $field_name) {
249
      $value = (bool) $form_state->getValue(['options', $field_name]);
250 251 252 253 254 255
      if ($node->$field_name->value != $value) {
        $fields[$field_name]->getConfig($type->id())->setDefaultValue($value)->save();
      }
    }

    $this->entityManager->clearCachedFieldDefinitions();
256
    $form_state->setRedirectUrl($type->urlInfo('collection'));
257 258 259
  }

}