EntityTestForm.php 2.57 KB
Newer Older
1 2 3
<?php
/**
 * @file
4
 * Definition of Drupal\entity_test\EntityTestForm.
5 6 7 8
 */

namespace Drupal\entity_test;

9
use Drupal\Core\Entity\ContentEntityForm;
10
use Drupal\Core\Form\FormStateInterface;
11
use Drupal\Core\Language\LanguageInterface;
12 13 14 15

/**
 * Form controller for the test entity edit forms.
 */
16
class EntityTestForm extends ContentEntityForm {
17 18

  /**
19
   * {@inheritdoc}
20
   */
21
  public function form(array $form, FormStateInterface $form_state) {
22 23
    $form = parent::form($form, $form_state);
    $entity = $this->entity;
24

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#default_value' => $entity->name->value,
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => TRUE,
      '#weight' => -10,
    );

    $form['user_id'] = array(
      '#type' => 'textfield',
      '#title' => 'UID',
      '#default_value' => $entity->user_id->target_id,
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => TRUE,
      '#weight' => -10,
    );

45 46 47
    $form['langcode'] = array(
      '#title' => t('Language'),
      '#type' => 'language_select',
48
      '#default_value' => $entity->getUntranslated()->language()->id,
49
      '#languages' => LanguageInterface::STATE_ALL,
50
    );
51

52
    // @todo: Is there a better way to check if an entity type is revisionable?
53
    if ($entity->getEntityType()->hasKey('revision') && !$entity->isNew()) {
54 55 56 57 58 59 60
      $form['revision'] = array(
        '#type' => 'checkbox',
        '#title' => t('Create new revision'),
        '#default_value' => $entity->isNewRevision(),
      );
    }

61
    return $form;
62 63
  }

64
  /**
65
   * {@inheritdoc}
66
   */
67 68
  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;
69 70

    // Save as a new revision if requested to do so.
71
    if (!$form_state->isValueEmpty('revision')) {
72 73 74
      $entity->setNewRevision();
    }

75 76 77
    $is_new = $entity->isNew();
    $entity->save();

78
    if ($is_new) {
79
     $message = t('%entity_type @id has been created.', array('@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()));
80 81
    }
    else {
82
      $message = t('%entity_type @id has been updated.', array('@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()));
83
    }
84 85 86
    drupal_set_message($message);

    if ($entity->id()) {
87
      $entity_type = $entity->getEntityTypeId();
88
      $form_state->setRedirect(
89
        "entity.$entity_type.edit_form",
90
        array($entity_type => $entity->id())
91
      );
92 93 94 95
    }
    else {
      // Error on save.
      drupal_set_message(t('The entity could not be saved.'), 'error');
96
      $form_state->setRebuild();
97 98
    }
  }
99

100
}