EntityFormController.php 15.5 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Entity\EntityFormController.
6 7
 */

8
namespace Drupal\Core\Entity;
9

10
use Drupal\entity\EntityFormDisplayInterface;
11 12
use Drupal\Core\Language\Language;

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/**
 * Base class for entity form controllers.
 */
class EntityFormController implements EntityFormControllerInterface {

  /**
   * The name of the current operation.
   *
   * Subclasses may use this to implement different behaviors depending on its
   * value.
   *
   * @var string
   */
  protected $operation;

28 29 30 31 32 33 34
  /**
   * The entity being used by this form.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $entity;

35
  /**
36 37
   * Constructs an EntityFormController object.
   *
38 39 40 41 42 43 44 45 46 47
   * @param string|null $operation
   *   (optional) The name of the current operation, defaults to NULL.
   */
  public function __construct($operation = NULL) {
    $this->setOperation($operation);
  }

  /**
   * Sets the operation for this form.
   *
48 49
   * @param string $operation
   *   The name of the current operation.
50
   */
51 52 53 54 55
  public function setOperation($operation) {
    // If NULL is passed, do not overwrite the operation.
    if ($operation) {
      $this->operation = $operation;
    }
56 57 58
  }

  /**
59
   * {@inheritdoc}
60
   */
61 62 63
  public function getBaseFormID() {
    return $this->entity->entityType() . '_form';
  }
64

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  /**
   * {@inheritdoc}
   */
  public function getFormID() {
    $entity_type = $this->entity->entityType();
    $bundle = $this->entity->bundle();
    $form_id = $entity_type;
    if ($bundle != $entity_type) {
      $form_id = $bundle . '_' . $form_id;
    }
    if ($this->operation != 'default') {
      $form_id = $form_id . '_' . $this->operation;
    }
    return $form_id . '_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, array &$form_state) {
    // During the initial form build, add this controller to the form state and
    // allow for initial preparation before form building and processing.
    if (!isset($form_state['controller'])) {
      $this->init($form_state);
89 90 91
    }

    // Retrieve the form array using the possibly updated entity in form state.
92
    $form = $this->form($form, $form_state);
93 94 95 96 97 98 99 100 101 102

    // Retrieve and add the form actions array.
    $actions = $this->actionsElement($form, $form_state);
    if (!empty($actions)) {
      $form['actions'] = $actions;
    }

    return $form;
  }

103 104 105 106 107 108 109 110 111 112 113 114
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, array &$form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, array &$form_state) {
  }

115 116 117
  /**
   * Initialize the form state and the entity before the first form build.
   */
118
  protected function init(array &$form_state) {
119 120 121
    // Add the controller to the form state so it can be easily accessed by
    // module-provided form handlers there.
    $form_state['controller'] = $this;
122
    $this->prepareEntity();
123 124 125 126 127 128 129 130 131 132 133 134 135 136

    // @todo Allow the usage of different form modes by exposing a hook and the
    // UI for them.
    $form_display = entity_get_render_form_display($this->entity, 'default');

    // Let modules alter the form display.
    $form_display_context = array(
      'entity_type' => $this->entity->entityType(),
      'bundle' => $this->entity->bundle(),
      'form_mode' => 'default',
    );
    \Drupal::moduleHandler()->alter('entity_form_display', $form_display, $form_display_context);

    $this->setFormDisplay($form_display, $form_state);
137 138 139 140 141
  }

  /**
   * Returns the actual form array to be built.
   *
142
   * @see Drupal\Core\Entity\EntityFormController::build()
143
   */
144 145
  public function form(array $form, array &$form_state) {
    $entity = $this->entity;
146
    // @todo Exploit the Field API to generate the default widgets for the
147 148 149
    // entity properties.
    $info = $entity->entityInfo();
    if (!empty($info['fieldable'])) {
150
      field_attach_form($entity, $form, $form_state, $this->getFormLangcode($form_state));
151
    }
152 153 154 155 156 157 158 159

    // Assign the weights configured in the form display.
    foreach ($this->getFormDisplay($form_state)->getComponents() as $name => $options) {
      if (isset($form[$name])) {
        $form[$name]['#weight'] = $options['weight'];
      }
    }

160 161 162 163 164 165 166 167 168
    if (!isset($form['langcode'])) {
      // If the form did not specify otherwise, default to keeping the existing
      // language of the entity or defaulting to the site default language for
      // new entities.
      $form['langcode'] = array(
        '#type' => 'value',
        '#value' => !$entity->isNew() ? $entity->langcode : language_default()->langcode,
      );
    }
169 170 171 172 173 174 175 176 177 178
    return $form;
  }

  /**
   * Returns the action form element for the current entity form.
   */
  protected function actionsElement(array $form, array &$form_state) {
    $element = $this->actions($form, $form_state);

    // We cannot delete an entity that has not been created yet.
179
    if ($this->entity->isNew()) {
180 181 182 183 184 185 186 187
      unset($element['delete']);
    }
    elseif (isset($element['delete'])) {
      // Move the delete action as last one, unless weights are explicitly
      // provided.
      $delete = $element['delete'];
      unset($element['delete']);
      $element['delete'] = $delete;
188 189 190 191 192 193
      $element['delete']['#button_type'] = 'danger';
    }

    if (isset($element['submit'])) {
      // Give the primary submit button a #button_type of primary.
      $element['submit']['#button_type'] = 'primary';
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    }

    $count = 0;
    foreach (element_children($element) as $action) {
      $element[$action] += array(
        '#type' => 'submit',
        '#weight' => ++$count * 5,
      );
    }

    if (!empty($element)) {
      $element['#type'] = 'actions';
    }

    return $element;
  }

  /**
   * Returns an array of supported actions for the current entity form.
   */
  protected function actions(array $form, array &$form_state) {
    return array(
      // @todo Rename the action key from submit to save.
      'submit' => array(
        '#value' => t('Save'),
        '#validate' => array(
          array($this, 'validate'),
        ),
        '#submit' => array(
          array($this, 'submit'),
          array($this, 'save'),
        ),
      ),
      'delete' => array(
        '#value' => t('Delete'),
        // No need to validate the form when deleting the entity.
        '#submit' => array(
          array($this, 'delete'),
        ),
      ),
      // @todo Consider introducing a 'preview' action here, since it is used by
      // many entity types.
    );
  }

  /**
240
   * Implements \Drupal\Core\Entity\EntityFormControllerInterface::validate().
241 242 243
   */
  public function validate(array $form, array &$form_state) {
    $entity = $this->buildEntity($form, $form_state);
244
    $entity_langcode = $entity->language()->langcode;
245

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    $violations = array();

    // @todo Simplify when all entity types are converted to EntityNG.
    if ($entity instanceof EntityNG) {
      foreach ($entity as $field_name => $field) {
        $field_violations = $field->validate();
        if (count($field_violations)) {
          $violations[$field_name] = $field_violations;
        }
      }
    }
    else {
      // For BC entities, iterate through each field instance and
      // instantiate NG items objects manually.
      $definitions = \Drupal::entityManager()->getFieldDefinitions($entity->entityType(), $entity->bundle());
      foreach (field_info_instances($entity->entityType(), $entity->bundle()) as $field_name => $instance) {
        $langcode = field_is_translatable($entity->entityType(), $instance->getField()) ? $entity_langcode : Language::LANGCODE_NOT_SPECIFIED;

        // Create the field object.
        $items = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
        // @todo Exception : calls setValue(), tries to set the 'formatted'
        // property.
        $field = \Drupal::typedData()->create($definitions[$field_name], $items, $field_name, $entity);
        $field_violations = $field->validate();
        if (count($field_violations)) {
          $violations[$field->getName()] = $field_violations;
        }
      }
    }

    // Map errors back to form elements.
    if ($violations) {
      foreach ($violations as $field_name => $field_violations) {
        $langcode = field_is_translatable($entity->entityType(), field_info_field($field_name)) ? $entity_langcode : Language::LANGCODE_NOT_SPECIFIED;
        $field_state = field_form_get_state($form['#parents'], $field_name, $langcode, $form_state);
        $field_state['constraint_violations'] = $field_violations;
        field_form_set_state($form['#parents'], $field_name, $langcode, $form_state, $field_state);
      }

      field_invoke_method('flagErrors', _field_invoke_widget_target($form_state['form_display']), $entity, $form, $form_state);
286 287 288 289 290 291 292 293 294
    }

    // @todo Remove this.
    // Execute legacy global validation handlers.
    unset($form_state['validate_handlers']);
    form_execute_handlers('validate', $form, $form_state);
  }

  /**
295
   * Implements \Drupal\Core\Entity\EntityFormControllerInterface::submit().
296 297 298 299 300 301 302 303 304 305 306 307 308
   *
   * This is the default entity object builder function. It is called before any
   * other submit handler to build the new entity object to be passed to the
   * following submit handlers. At this point of the form workflow the entity is
   * validated and the form state can be updated, this way the subsequently
   * invoked handlers can retrieve a regular entity object to act on.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param array $form_state
   *   A reference to a keyed array containing the current state of the form.
   */
  public function submit(array $form, array &$form_state) {
309 310 311
    // Remove button and internal Form API values from submitted values.
    form_state_values_clean($form_state);

312
    $this->updateFormLangcode($form_state);
313
    $this->submitEntityLanguage($form, $form_state);
314 315
    $this->entity = $this->buildEntity($form, $form_state);
    return $this->entity;
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
  }

  /**
   * Form submission handler for the 'save' action.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param array $form_state
   *   A reference to a keyed array containing the current state of the form.
   */
  public function save(array $form, array &$form_state) {
    // @todo Perform common save operations.
  }

  /**
   * Form submission handler for the 'delete' action.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param array $form_state
   *   A reference to a keyed array containing the current state of the form.
   */
  public function delete(array $form, array &$form_state) {
    // @todo Perform common delete operations.
  }

  /**
343
   * Implements \Drupal\Core\Entity\EntityFormControllerInterface::getFormLangcode().
344
   */
345
  public function getFormLangcode(array $form_state) {
346
    $entity = $this->entity;
347
    $translations = $entity->getTranslationLanguages();
348 349 350 351 352 353 354 355

    if (!empty($form_state['langcode'])) {
      $langcode = $form_state['langcode'];
    }
    else {
      // If no form langcode was provided we default to the current content
      // language and inspect existing translations to find a valid fallback,
      // if any.
356
      $langcode = language(Language::TYPE_CONTENT)->langcode;
357 358 359 360 361 362 363 364 365
      $fallback = language_multilingual() ? language_fallback_get_candidates() : array();
      while (!empty($langcode) && !isset($translations[$langcode])) {
        $langcode = array_shift($fallback);
      }
    }

    // If the site is not multilingual or no translation for the given form
    // language is available, fall back to the entity language.
    return !empty($langcode) ? $langcode : $entity->language()->langcode;
366 367
  }

368
  /**
369
   * Implements \Drupal\Core\Entity\EntityFormControllerInterface::isDefaultFormLangcode().
370
   */
371
  public function isDefaultFormLangcode(array $form_state) {
372
    return $this->getFormLangcode($form_state) == $this->entity->language()->langcode;
373 374 375
  }

  /**
376
   * Updates the form language to reflect any change to the entity language.
377 378
   *
   * @param array $form_state
379
   *   A keyed array containing the current state of the form.
380
   */
381
  protected function updateFormLangcode(array $form_state) {
382 383 384 385
    // Update the form language as it might have changed.
    if (isset($form_state['values']['langcode']) && $this->isDefaultFormLangcode($form_state)) {
      $form_state['langcode'] = $form_state['values']['langcode'];
    }
386
  }
387

388 389 390 391 392 393 394 395 396
  /**
   * Handle possible entity language changes.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param array $form_state
   *   A reference to a keyed array containing the current state of the form.
   */
  protected function submitEntityLanguage(array $form, array &$form_state) {
397
    $entity = $this->entity;
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    $entity_type = $entity->entityType();

    if (field_has_translation_handler($entity_type)) {
      $form_langcode = $this->getFormLangcode($form_state);

      // If we are editing the default language values, we use the submitted
      // entity language as the new language for fields to handle any language
      // change. Otherwise the current form language is the proper value, since
      // in this case it is not supposed to change.
      $current_langcode = $entity->language()->langcode == $form_langcode ? $form_state['values']['langcode'] : $form_langcode;

      foreach (field_info_instances($entity_type, $entity->bundle()) as $instance) {
        $field_name = $instance['field_name'];
        $field = field_info_field($field_name);
        $previous_langcode = $form[$field_name]['#language'];

        // Handle a possible language change: new language values are inserted,
        // previous ones are deleted.
        if ($field['translatable'] && $previous_langcode != $current_langcode) {
          $form_state['values'][$field_name][$current_langcode] = $form_state['values'][$field_name][$previous_langcode];
          $form_state['values'][$field_name][$previous_langcode] = array();
        }
      }
    }
  }

424
  /**
425
   * Implements \Drupal\Core\Entity\EntityFormControllerInterface::buildEntity().
426 427
   */
  public function buildEntity(array $form, array &$form_state) {
428
    $entity = clone $this->entity;
429 430 431 432
    // If you submit a form, the form state comes from caching, which forces
    // the controller to be the one before caching. Ensure to have the
    // controller of the current request.
    $form_state['controller'] = $this;
433
    // @todo Move entity_form_submit_build_entity() here.
434
    // @todo Exploit the Field API to process the submitted entity field.
435 436 437 438 439
    entity_form_submit_build_entity($entity->entityType(), $entity, $form, $form_state);
    return $entity;
  }

  /**
440
   * Implements \Drupal\Core\Entity\EntityFormControllerInterface::getEntity().
441
   */
442 443
  public function getEntity() {
    return $this->entity;
444 445 446
  }

  /**
447
   * Implements \Drupal\Core\Entity\EntityFormControllerInterface::setEntity().
448
   */
449 450 451
  public function setEntity(EntityInterface $entity) {
    $this->entity = $entity;
    return $this;
452 453 454 455 456
  }

  /**
   * Prepares the entity object before the form is built first.
   */
457
  protected function prepareEntity() {
458 459 460
    // @todo Perform common prepare operations and add a hook.
  }

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
  /**
   * {@inheritdoc}
   */
  public function getFormDisplay(array $form_state) {
    return isset($form_state['form_display']) ? $form_state['form_display'] : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function setFormDisplay(EntityFormDisplayInterface $form_display, array &$form_state) {
    $form_state['form_display'] = $form_display;
    return $this;
  }

476
  /**
477
   * Implements \Drupal\Core\Entity\EntityFormControllerInterface::getOperation().
478 479 480 481 482
   */
  public function getOperation() {
    return $this->operation;
  }
}