summaryrefslogtreecommitdiffstats
path: root/core/modules/system/tests/modules/entity_test/src/EntityTestForm.php
blob: d471d6058200f16b2f1c506795b4a5d45d125594 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
<?php

namespace Drupal\entity_test;

use Drupal\Component\Utility\Random;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form controller for the test entity edit forms.
 *
 * @internal
 */
class EntityTestForm extends ContentEntityForm {

  /**
   * {@inheritdoc}
   */
  protected function prepareEntity() {
    if (empty($this->entity->name->value)) {
      // Assign a random name to new EntityTest entities, to avoid repetition in
      // tests.
      $random = new Random();
      $this->entity->name->value = $random->name();
    }
  }

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

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

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    try {
      $entity = $this->entity;

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

      $is_new = $entity->isNew();
      $entity->save();

      if ($is_new) {
        $message = t('%entity_type @id has been created.', ['@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()]);
      }
      else {
        $message = t('%entity_type @id has been updated.', ['@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()]);
      }
      $this->messenger()->addStatus($message);

      if ($entity->id()) {
        $entity_type = $entity->getEntityTypeId();
        $form_state->setRedirect(
          "entity.$entity_type.edit_form",
          [$entity_type => $entity->id()]
        );
      }
      else {
        // Error on save.
        $this->messenger()->addError($this->t('The entity could not be saved.'));
        $form_state->setRebuild();
      }
    }
    catch (\Exception $e) {
      \Drupal::state()->set('entity_test.form.save.exception', get_class($e) . ': ' . $e->getMessage());
    }
  }

}