NodeFormController.php 18.3 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Definition of Drupal\node\NodeFormController.
 */

namespace Drupal\node;

10
use Drupal\Component\Utility\NestedArray;
11
use Drupal\Core\Datetime\DrupalDateTime;
12
use Drupal\Core\Entity\ContentEntityFormController;
13
use Drupal\Core\Language\Language;
14
use Drupal\Component\Utility\String;
15 16 17 18

/**
 * Form controller for the node edit forms.
 */
19
class NodeFormController extends ContentEntityFormController {
20

21 22 23 24 25 26 27
  /**
   * Default settings for this content/node type.
   *
   * @var array
   */
  protected $settings;

28
  /**
29
   * {@inheritdoc}
30
   */
31 32
  protected function prepareEntity() {
    $node = $this->entity;
33
    // Set up default values, if required.
34 35 36 37 38 39 40 41
    $type = entity_load('node_type', $node->bundle());
    $this->settings = $type->getModuleSettings('node');
    $this->settings += array(
      'options' => array('status', 'promote'),
      'preview' => DRUPAL_OPTIONAL,
      'submitted' => TRUE,
    );

42
    // If this is a new node, fill in the default values.
43
    if ($node->isNew()) {
44 45
      foreach (array('status', 'promote', 'sticky') as $key) {
        // Multistep node forms might have filled in something already.
46
        if ($node->$key->isEmpty()) {
47
          $node->$key = (int) in_array($key, $this->settings['options']);
48 49
        }
      }
50
      $node->setAuthorId(\Drupal::currentUser()->id());
51
      $node->setCreatedTime(REQUEST_TIME);
52 53
    }
    else {
54
      $node->date = format_date($node->getCreatedTime(), 'custom', 'Y-m-d H:i:s O');
55 56 57 58
      // Remove the log message from the original node entity.
      $node->log = NULL;
    }
    // Always use the default revision setting.
59
    $node->setNewRevision(in_array('revision', $this->settings['options']));
60 61 62
  }

  /**
63
   * Overrides Drupal\Core\Entity\EntityFormController::form().
64
   */
65 66
  public function form(array $form, array &$form_state) {
    $node = $this->entity;
67

68
    if ($this->operation == 'edit') {
69
      $form['#title'] = $this->t('<em>Edit @type</em> @title', array('@type' => node_get_type_label($node), '@title' => $node->label()));
70 71
    }

72
    $user_config = \Drupal::config('user.settings');
73 74 75 76
    // Some special stuff when previewing a node.
    if (isset($form_state['node_preview'])) {
      $form['#prefix'] = $form_state['node_preview'];
      $node->in_preview = TRUE;
77
      $form['#title'] = $this->t('Preview');
78 79 80 81 82 83 84 85
    }
    else {
      unset($node->in_preview);
    }

    // Override the default CSS class name, since the user-defined node type
    // name in 'TYPE-node-form' potentially clashes with third-party class
    // names.
86
    $form['#attributes']['class'][0] = drupal_html_class('node-' . $node->getType() . '-form');
87 88 89 90 91 92 93 94 95 96 97 98 99

    // Basic node information.
    // These elements are just values so they are not even sent to the client.
    foreach (array('nid', 'vid', 'uid', 'created', 'type') as $key) {
      $form[$key] = array(
        '#type' => 'value',
        '#value' => isset($node->$key) ? $node->$key : NULL,
      );
    }

    // Changed must be sent to the client, for later overwrite error checking.
    $form['changed'] = array(
      '#type' => 'hidden',
100
      '#default_value' => $node->getChangedTime(),
101 102
    );

103
    $language_configuration = module_invoke('language', 'get_default_configuration', 'node', $node->getType());
104 105 106
    $form['langcode'] = array(
      '#title' => t('Language'),
      '#type' => 'language_select',
107
      '#default_value' => $node->getUntranslated()->language()->id,
108
      '#languages' => Language::STATE_ALL,
109
      '#access' => isset($language_configuration['language_show']) && $language_configuration['language_show'],
110
    );
111

112
    $form['advanced'] = array(
113
      '#type' => 'vertical_tabs',
114
      '#attributes' => array('class' => array('entity-meta')),
115 116 117
      '#weight' => 99,
    );

118 119
    // Add a log field if the "Create new revision" option is checked, or if
    // the current user has the ability to check that option.
120
    $form['revision_information'] = array(
121 122
      '#type' => 'details',
      '#group' => 'advanced',
123
      '#title' => t('Revision information'),
124
      // Collapsed by default when "Create new revision" is unchecked.
125
      '#collapsed' => !$node->isNewRevision(),
126 127 128 129 130 131 132
      '#attributes' => array(
        'class' => array('node-form-revision-information'),
      ),
      '#attached' => array(
        'js' => array(drupal_get_path('module', 'node') . '/node.js'),
      ),
      '#weight' => 20,
133
      '#access' => $node->isNewRevision() || user_access('administer nodes'),
134 135
    );

136
    $form['revision_information']['revision']['revision'] = array(
137 138
      '#type' => 'checkbox',
      '#title' => t('Create new revision'),
139
      '#default_value' => $node->isNewRevision(),
140 141 142
      '#access' => user_access('administer nodes'),
    );

143
    $form['revision_information']['revision']['log'] = array(
144 145 146
      '#type' => 'textarea',
      '#title' => t('Revision log message'),
      '#rows' => 4,
147
      '#default_value' => !empty($node->log->value) ? $node->log->value : '',
148
      '#description' => t('Briefly describe the changes you have made.'),
149 150 151 152 153
      '#states' => array(
        'visible' => array(
          ':input[name="revision"]' => array('checked' => TRUE),
        ),
      ),
154 155 156 157
    );

    // Node author information for administrators.
    $form['author'] = array(
158
      '#type' => 'details',
159 160
      '#access' => user_access('administer nodes'),
      '#title' => t('Authoring information'),
161
      '#collapsed' => TRUE,
162
      '#group' => 'advanced',
163 164 165 166 167 168 169 170
      '#attributes' => array(
        'class' => array('node-form-author'),
      ),
      '#attached' => array(
        'js' => array(
          drupal_get_path('module', 'node') . '/node.js',
          array(
            'type' => 'setting',
171
            'data' => array('anonymous' => $user_config->get('anonymous')),
172 173 174 175 176 177 178 179 180 181
          ),
        ),
      ),
      '#weight' => 90,
    );

    $form['author']['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Authored by'),
      '#maxlength' => 60,
182
      '#autocomplete_route_name' => 'user.autocomplete',
183
      '#default_value' => $node->getAuthorId()? $node->getAuthor()->getUsername() : '',
184
      '#weight' => -1,
185
      '#description' => t('Leave blank for %anonymous.', array('%anonymous' => $user_config->get('anonymous'))),
186 187
    );
    $form['author']['date'] = array(
188
      '#type' => 'textfield',
189
      '#title' => t('Authored on'),
190
      '#maxlength' => 25,
191
      '#description' => t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', array('%time' => !empty($node->date) ? date_format(date_create($node->date), 'Y-m-d H:i:s O') : format_date($node->getCreatedTime(), 'custom', 'Y-m-d H:i:s O'), '%timezone' => !empty($node->date) ? date_format(date_create($node->date), 'O') : format_date($node->getCreatedTime(), 'custom', 'O'))),
192 193 194 195 196
      '#default_value' => !empty($node->date) ? $node->date : '',
    );

    // Node options for administrators.
    $form['options'] = array(
197
      '#type' => 'details',
198
      '#access' => user_access('administer nodes'),
199
      '#title' => t('Promotion options'),
200
      '#collapsed' => TRUE,
201
      '#group' => 'advanced',
202 203 204 205 206 207 208 209 210 211 212 213
      '#attributes' => array(
        'class' => array('node-form-options'),
      ),
      '#attached' => array(
        'js' => array(drupal_get_path('module', 'node') . '/node.js'),
      ),
      '#weight' => 95,
    );

    $form['options']['promote'] = array(
      '#type' => 'checkbox',
      '#title' => t('Promoted to front page'),
214
      '#default_value' => $node->isPromoted(),
215 216 217 218 219
    );

    $form['options']['sticky'] = array(
      '#type' => 'checkbox',
      '#title' => t('Sticky at top of lists'),
220
      '#default_value' => $node->isSticky(),
221 222 223 224 225 226 227 228 229 230 231 232 233
    );

    // This form uses a button-level #submit handler for the form's main submit
    // action. node_form_submit() manually invokes all form-level #submit
    // handlers of the form. Without explicitly setting #submit, Form API would
    // auto-detect node_form_submit() as submit handler, but that is the
    // button-level #submit handler for the 'Save' action.
    $form += array('#submit' => array());

    return parent::form($form, $form_state, $node);
  }

  /**
234
   * Overrides Drupal\Core\Entity\EntityFormController::actions().
235
   */
236 237
  protected function actions(array $form, array &$form_state) {
    $element = parent::actions($form, $form_state);
238
    $node = $this->entity;
239
    $preview_mode = $this->settings['preview'];
240

241
    $element['submit']['#access'] = $preview_mode != DRUPAL_REQUIRED || (!form_get_errors($form_state) && isset($form_state['node_preview']));
242

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    // If saving is an option, privileged users get dedicated form submit
    // buttons to adjust the publishing status while saving in one go.
    // @todo This adjustment makes it close to impossible for contributed
    //   modules to integrate with "the Save operation" of this form. Modules
    //   need a way to plug themselves into 1) the ::submit() step, and
    //   2) the ::save() step, both decoupled from the pressed form button.
    if ($element['submit']['#access'] && user_access('administer nodes')) {
      // isNew | prev status » default   & publish label             & unpublish label
      // 1     | 1           » publish   & Save and publish          & Save as unpublished
      // 1     | 0           » unpublish & Save and publish          & Save as unpublished
      // 0     | 1           » publish   & Save and keep published   & Save and unpublish
      // 0     | 0           » unpublish & Save and keep unpublished & Save and publish

      // Add a "Publish" button.
      $element['publish'] = $element['submit'];
      $element['publish']['#dropbutton'] = 'save';
      if ($node->isNew()) {
        $element['publish']['#value'] = t('Save and publish');
261
      }
262
      else {
263
        $element['publish']['#value'] = $node->isPublished() ? t('Save and keep published') : t('Save and publish');
264 265 266 267 268 269 270 271 272 273 274
      }
      $element['publish']['#weight'] = 0;
      array_unshift($element['publish']['#submit'], array($this, 'publish'));

      // Add a "Unpublish" button.
      $element['unpublish'] = $element['submit'];
      $element['unpublish']['#dropbutton'] = 'save';
      if ($node->isNew()) {
        $element['unpublish']['#value'] = t('Save as unpublished');
      }
      else {
275
        $element['unpublish']['#value'] = !$node->isPublished() ? t('Save and keep unpublished') : t('Save and unpublish');
276 277 278
      }
      $element['unpublish']['#weight'] = 10;
      array_unshift($element['unpublish']['#submit'], array($this, 'unpublish'));
279

280
      // If already published, the 'publish' button is primary.
281
      if ($node->isPublished()) {
282 283 284 285 286 287 288
        unset($element['unpublish']['#button_type']);
      }
      // Otherwise, the 'unpublish' button is primary and should come first.
      else {
        unset($element['publish']['#button_type']);
        $element['unpublish']['#weight'] = -10;
      }
289

290 291 292
      // Remove the "Save" button.
      $element['submit']['#access'] = FALSE;
    }
293 294

    $element['preview'] = array(
295
      '#access' => $preview_mode != DRUPAL_DISABLED && ($node->access('create') || $node->access('update')),
296
      '#value' => t('Preview'),
297
      '#weight' => 20,
298 299 300 301 302 303 304 305 306
      '#validate' => array(
        array($this, 'validate'),
      ),
      '#submit' => array(
        array($this, 'submit'),
        array($this, 'preview'),
      ),
    );

307
    $element['delete']['#access'] = $node->access('delete');
308
    $element['delete']['#weight'] = 100;
309 310 311 312 313

    return $element;
  }

  /**
314
   * Overrides Drupal\Core\Entity\EntityFormController::validate().
315 316 317 318
   */
  public function validate(array $form, array &$form_state) {
    $node = $this->buildEntity($form, $form_state);

319
    if ($node->id() && (node_last_changed($node->id(), $this->getFormLangcode($form_state)) > $node->getChangedTime())) {
320
      $this->setFormError('changed', $form_state, $this->t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
321 322 323
    }

    // Validate the "authored by" field.
324
    if (!empty($form_state['values']['name']) && !($account = user_load_by_name($form_state['values']['name']))) {
325 326 327
      // The use of empty() is mandatory in the context of usernames
      // as the empty string denotes the anonymous user. In case we
      // are dealing with an anonymous user we set the user ID to 0.
328
      $this->setFormError('name', $form_state, $this->t('The username %name does not exist.', array('%name' => $form_state['values']['name'])));
329 330 331
    }

    // Validate the "authored on" field.
332
    // The date element contains the date object.
333 334
    $date = $node->date instanceof DrupalDateTime ? $node->date : new DrupalDateTime($node->date);
    if ($date->hasErrors()) {
335
      $this->setFormError('date', $form_state, $this->t('You have to specify a valid date.'));
336 337
    }

338 339
    // Invoke hook_node_validate() for validation needed by modules.
    // Can't use module_invoke_all(), because $form_state must
340
    // be receivable by reference.
341
    foreach (\Drupal::moduleHandler()->getImplementations('node_validate') as $module) {
342 343 344 345 346 347 348 349 350 351 352 353 354 355
      $function = $module . '_node_validate';
      $function($node, $form, $form_state);
    }

    parent::validate($form, $form_state);
  }

  /**
   * Updates the node object by processing the submitted values.
   *
   * This function can be called by a "Next" button of a wizard to update the
   * form state's entity with the current step's values before proceeding to the
   * next step.
   *
356
   * Overrides Drupal\Core\Entity\EntityFormController::submit().
357 358 359 360 361
   */
  public function submit(array $form, array &$form_state) {
    // Build the node object from the submitted values.
    $node = parent::submit($form, $form_state);

362 363 364
    // Save as a new revision if requested to do so.
    if (!empty($form_state['values']['revision'])) {
      $node->setNewRevision();
365 366
      // If a new revision is created, save the current user as revision author.
      $node->setRevisionCreationTime(REQUEST_TIME);
367
      $node->setRevisionAuthorId(\Drupal::currentUser()->id());
368 369
    }

370
    $node->validated = TRUE;
371
    foreach (\Drupal::moduleHandler()->getImplementations('node_submit') as $module) {
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
      $function = $module . '_node_submit';
      $function($node, $form, $form_state);
    }

    return $node;
  }

  /**
   * Form submission handler for the 'preview' action.
   *
   * @param $form
   *   An associative array containing the structure of the form.
   * @param $form_state
   *   A reference to a keyed array containing the current state of the form.
   */
  public function preview(array $form, array &$form_state) {
388 389 390
    // @todo Remove this: we should not have explicit includes in autoloaded
    //   classes.
    module_load_include('inc', 'node', 'node.pages');
391
    $form_state['node_preview'] = node_preview($this->entity, $form_state);
392 393 394
    $form_state['rebuild'] = TRUE;
  }

395 396 397 398 399 400 401 402 403
  /**
   * Form submission handler for the 'publish' action.
   *
   * @param $form
   *   An associative array containing the structure of the form.
   * @param $form_state
   *   A reference to a keyed array containing the current state of the form.
   */
  public function publish(array $form, array &$form_state) {
404
    $node = $this->entity;
405
    $node->setPublished(TRUE);
406 407 408 409 410 411 412 413 414 415 416 417
    return $node;
  }

  /**
   * Form submission handler for the 'unpublish' action.
   *
   * @param $form
   *   An associative array containing the structure of the form.
   * @param $form_state
   *   A reference to a keyed array containing the current state of the form.
   */
  public function unpublish(array $form, array &$form_state) {
418
    $node = $this->entity;
419
    $node->setPublished(FALSE);
420 421 422
    return $node;
  }

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
  /**
   * {@inheritdoc}
   */
  public function buildEntity(array $form, array &$form_state) {
    $entity = parent::buildEntity($form, $form_state);
    // A user might assign the node author by entering a user name in the node
    // form, which we then need to translate to a user ID.
    if (!empty($form_state['values']['name']) && $account = user_load_by_name($form_state['values']['name'])) {
      $entity->setAuthorId($account->id());
    }
    else {
      $entity->setAuthorId(0);
    }

    if (!empty($form_state['values']['date']) && $form_state['values']['date'] instanceOf DrupalDateTime) {
      $entity->setCreatedTime($form_state['values']['date']->getTimestamp());
    }
    else {
      $entity->setCreatedTime(REQUEST_TIME);
    }
    return $entity;
  }


447
  /**
448
   * Overrides Drupal\Core\Entity\EntityFormController::save().
449 450
   */
  public function save(array $form, array &$form_state) {
451
    $node = $this->entity;
452
    $insert = $node->isNew();
453
    $node->save();
454
    $node_link = l(t('view'), 'node/' . $node->id());
455
    $watchdog_args = array('@type' => $node->getType(), '%title' => $node->label());
456
    $t_args = array('@type' => node_get_type_label($node), '%title' => $node->label());
457 458 459 460 461 462 463 464 465 466

    if ($insert) {
      watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
      drupal_set_message(t('@type %title has been created.', $t_args));
    }
    else {
      watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
      drupal_set_message(t('@type %title has been updated.', $t_args));
    }

467 468 469
    if ($node->id()) {
      $form_state['values']['nid'] = $node->id();
      $form_state['nid'] = $node->id();
470 471 472 473 474 475 476 477 478 479 480
      if ($node->access('view')) {
        $form_state['redirect_route'] = array(
          'route_name' => 'node.view',
          'route_parameters' => array(
            'node' => $node->id(),
          ),
        );
      }
      else {
        $form_state['redirect_route']['route_name'] = '<front>';
      }
481 482 483 484 485 486 487 488 489
    }
    else {
      // In the unlikely case something went wrong on save, the node will be
      // rebuilt and node form redisplayed the same way as in preview.
      drupal_set_message(t('The post could not be saved.'), 'error');
      $form_state['rebuild'] = TRUE;
    }

    // Clear the page and block caches.
490
    cache_invalidate_tags(array('content' => TRUE));
491 492 493
  }

  /**
494
   * Overrides Drupal\Core\Entity\EntityFormController::delete().
495 496 497
   */
  public function delete(array $form, array &$form_state) {
    $destination = array();
498 499
    $query = \Drupal::request()->query;
    if ($query->has('destination')) {
500
      $destination = drupal_get_destination();
501
      $query->remove('destination');
502
    }
503 504 505 506 507 508 509 510 511
    $form_state['redirect_route'] = array(
      'route_name' => 'node.delete_confirm',
      'route_parameters' => array(
        'node' => $this->entity->id(),
      ),
      'options' => array(
        'query' => $destination,
      ),
    );
512
  }
513

514
}