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