e4c51143c85a3f0947a669a23c63cf0f9445afcf
[yaffs-website] / web / core / modules / system / tests / modules / entity_test / src / EntityTestForm.php
1 <?php
2
3 namespace Drupal\entity_test;
4
5 use Drupal\Component\Utility\Random;
6 use Drupal\Core\Entity\ContentEntityForm;
7 use Drupal\Core\Form\FormStateInterface;
8
9 /**
10  * Form controller for the test entity edit forms.
11  */
12 class EntityTestForm extends ContentEntityForm {
13
14   /**
15    * {@inheritdoc}
16    */
17   protected function prepareEntity() {
18     if (empty($this->entity->name->value)) {
19       // Assign a random name to new EntityTest entities, to avoid repetition in
20       // tests.
21       $random = new Random();
22       $this->entity->name->value = $random->name();
23     }
24   }
25
26   /**
27    * {@inheritdoc}
28    */
29   public function form(array $form, FormStateInterface $form_state) {
30     $form = parent::form($form, $form_state);
31     $entity = $this->entity;
32
33     // @todo: Is there a better way to check if an entity type is revisionable?
34     if ($entity->getEntityType()->hasKey('revision') && !$entity->isNew()) {
35       $form['revision'] = [
36         '#type' => 'checkbox',
37         '#title' => t('Create new revision'),
38         '#default_value' => $entity->isNewRevision(),
39       ];
40     }
41
42     return $form;
43   }
44
45   /**
46    * {@inheritdoc}
47    */
48   public function save(array $form, FormStateInterface $form_state) {
49     try {
50       $entity = $this->entity;
51
52       // Save as a new revision if requested to do so.
53       if (!$form_state->isValueEmpty('revision')) {
54         $entity->setNewRevision();
55       }
56
57       $is_new = $entity->isNew();
58       $entity->save();
59
60       if ($is_new) {
61         $message = t('%entity_type @id has been created.', ['@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()]);
62       }
63       else {
64         $message = t('%entity_type @id has been updated.', ['@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()]);
65       }
66       drupal_set_message($message);
67
68       if ($entity->id()) {
69         $entity_type = $entity->getEntityTypeId();
70         $form_state->setRedirect(
71           "entity.$entity_type.edit_form",
72           [$entity_type => $entity->id()]
73         );
74       }
75       else {
76         // Error on save.
77         drupal_set_message(t('The entity could not be saved.'), 'error');
78         $form_state->setRebuild();
79       }
80     }
81     catch (\Exception $e) {
82       \Drupal::state()->set('entity_test.form.save.exception', get_class($e) . ': ' . $e->getMessage());
83     }
84   }
85
86 }