EntityTestForm.php 2.31 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\entity_test;

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 18 19 20 21 22 23 24 25 26 27
  /**
   * {@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();
    }
  }

28
  /**
29
   * {@inheritdoc}
30
   */
31
  public function form(array $form, FormStateInterface $form_state) {
32 33
    $form = parent::form($form, $form_state);
    $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 39 40
        '#type' => 'checkbox',
        '#title' => t('Create new revision'),
        '#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 52
    try {
      $entity = $this->entity;
53

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

59 60
      $is_new = $entity->isNew();
      $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 71 72 73
      if ($entity->id()) {
        $entity_type = $entity->getEntityTypeId();
        $form_state->setRedirect(
          "entity.$entity_type.edit_form",
74
          [$entity_type => $entity->id()]
75 76 77 78
        );
      }
      else {
        // Error on save.
79
        $this->messenger()->addError($this->t('The entity could not be saved.'));
80 81
        $form_state->setRebuild();
      }
82
    }
83 84
    catch (\Exception $e) {
      \Drupal::state()->set('entity_test.form.save.exception', get_class($e) . ': ' . $e->getMessage());
85 86
    }
  }
87

88
}