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.
12 class EntityTestForm extends ContentEntityForm {
17 protected function prepareEntity() {
18 if (empty($this->entity->name->value)) {
19 // Assign a random name to new EntityTest entities, to avoid repetition in
21 $random = new Random();
22 $this->entity->name->value = $random->name();
29 public function form(array $form, FormStateInterface $form_state) {
30 $form = parent::form($form, $form_state);
31 $entity = $this->entity;
33 // @todo: Is there a better way to check if an entity type is revisionable?
34 if ($entity->getEntityType()->hasKey('revision') && !$entity->isNew()) {
36 '#type' => 'checkbox',
37 '#title' => t('Create new revision'),
38 '#default_value' => $entity->isNewRevision(),
48 public function save(array $form, FormStateInterface $form_state) {
50 $entity = $this->entity;
52 // Save as a new revision if requested to do so.
53 if (!$form_state->isValueEmpty('revision')) {
54 $entity->setNewRevision();
57 $is_new = $entity->isNew();
61 $message = t('%entity_type @id has been created.', ['@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()]);
64 $message = t('%entity_type @id has been updated.', ['@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()]);
66 drupal_set_message($message);
69 $entity_type = $entity->getEntityTypeId();
70 $form_state->setRedirect(
71 "entity.$entity_type.edit_form",
72 [$entity_type => $entity->id()]
77 drupal_set_message(t('The entity could not be saved.'), 'error');
78 $form_state->setRebuild();
81 catch (\Exception $e) {
82 \Drupal::state()->set('entity_test.form.save.exception', get_class($e) . ': ' . $e->getMessage());