3 namespace Drupal\entity_test;
5 use Drupal\Component\Utility\Random;
6 use Drupal\Core\Entity\ContentEntityForm;
7 use Drupal\Core\Form\FormStateInterface;
10 * Form controller for the test entity edit forms.
14 class EntityTestForm extends ContentEntityForm {
19 protected function prepareEntity() {
20 if (empty($this->entity->name->value)) {
21 // Assign a random name to new EntityTest entities, to avoid repetition in
23 $random = new Random();
24 $this->entity->name->value = $random->name();
31 public function form(array $form, FormStateInterface $form_state) {
32 $form = parent::form($form, $form_state);
33 $entity = $this->entity;
35 // @todo: Is there a better way to check if an entity type is revisionable?
36 if ($entity->getEntityType()->hasKey('revision') && !$entity->isNew()) {
38 '#type' => 'checkbox',
39 '#title' => t('Create new revision'),
40 '#default_value' => $entity->isNewRevision(),
50 public function save(array $form, FormStateInterface $form_state) {
52 $entity = $this->entity;
54 // Save as a new revision if requested to do so.
55 if (!$form_state->isValueEmpty('revision')) {
56 $entity->setNewRevision();
59 $is_new = $entity->isNew();
63 $message = t('%entity_type @id has been created.', ['@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()]);
66 $message = t('%entity_type @id has been updated.', ['@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()]);
68 $this->messenger()->addStatus($message);
71 $entity_type = $entity->getEntityTypeId();
72 $form_state->setRedirect(
73 "entity.$entity_type.edit_form",
74 [$entity_type => $entity->id()]
79 $this->messenger()->addError($this->t('The entity could not be saved.'));
80 $form_state->setRebuild();
83 catch (\Exception $e) {
84 \Drupal::state()->set('entity_test.form.save.exception', get_class($e) . ': ' . $e->getMessage());