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

/**
 * @file
5
 * Contains \Drupal\node\NodeTypeForm.
6 7 8 9
 */

namespace Drupal\node;

10
use Drupal\Core\Entity\EntityForm;
11
use Drupal\Core\Entity\EntityManagerInterface;
12
use Drupal\Core\Entity\EntityTypeInterface;
13
use Drupal\Core\Form\FormStateInterface;
14
use Drupal\Core\Url;
15
use Drupal\language\Entity\ContentLanguageSettings;
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17 18 19 20

/**
 * Form controller for node type forms.
 */
21
class NodeTypeForm extends EntityForm {
22

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * Constructs the NodeTypeForm object.
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager
   */
  public function __construct(EntityManagerInterface $entity_manager) {
    $this->entityManager = $entity_manager;
  }

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

49 50 51
  /**
   * {@inheritdoc}
   */
52
  public function form(array $form, FormStateInterface $form_state) {
53 54 55 56
    $form = parent::form($form, $form_state);

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

    $form['name'] = array(
      '#title' => t('Name'),
      '#type' => 'textfield',
75
      '#default_value' => $type->label(),
76
      '#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.'),
77 78 79 80 81 82 83
      '#required' => TRUE,
      '#size' => 30,
    );

    $form['type'] = array(
      '#type' => 'machine_name',
      '#default_value' => $type->id(),
84
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
85 86
      '#disabled' => $type->isLocked(),
      '#machine_name' => array(
87
        'exists' => ['Drupal\node\Entity\NodeType', 'load'],
88 89 90
        'source' => array('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.', array(
91
        '%node-add' => t('Add content'),
92 93 94 95 96 97
      )),
    );

    $form['description'] = array(
      '#title' => t('Description'),
      '#type' => 'textarea',
98
      '#default_value' => $type->getDescription(),
99
      '#description' => t('This text will be displayed on the <em>Add new content</em> page.'),
100 101 102 103 104
    );

    $form['additional_settings'] = array(
      '#type' => 'vertical_tabs',
      '#attached' => array(
105
        'library' => array('node/drupal.content_types'),
106 107 108 109 110 111 112
      ),
    );

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

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

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

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

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

  /**
   * {@inheritdoc}
   */
219
  public function save(array $form, FormStateInterface $form_state) {
220
    $type = $this->entity;
221
    $type->setNewRevision($form_state->getValue(array('options', 'revision')));
222 223
    $type->set('type', trim($type->id()));
    $type->set('name', trim($type->label()));
224 225 226 227 228 229 230 231 232

    $status = $type->save();

    $t_args = array('%name' => $type->label());

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

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

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

}