Newer
Older
Angie Byron
committed
<?php
namespace Drupal\entity_test;
Alex Pott
committed
use Drupal\Component\Utility\Random;
Alex Pott
committed
use Drupal\Core\Entity\ContentEntityForm;
Dries Buytaert
committed
use Drupal\Core\Form\FormStateInterface;
Angie Byron
committed
/**
* Form controller for the test entity edit forms.
*
* @internal
Angie Byron
committed
*/
Alex Pott
committed
class EntityTestForm extends ContentEntityForm {
Angie Byron
committed
Alex Pott
committed
/**
* {@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();
}
}
Angie Byron
committed
/**
Dries Buytaert
committed
* {@inheritdoc}
Angie Byron
committed
*/
Dries Buytaert
committed
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$entity = $this->entity;
Angie Byron
committed
// @todo: Is there a better way to check if an entity type is revisionable?
Alex Pott
committed
if ($entity->getEntityType()->hasKey('revision') && !$entity->isNew()) {
$form['revision'] = [
'#type' => 'checkbox',
'#title' => t('Create new revision'),
'#default_value' => $entity->isNewRevision(),
];
}
Angie Byron
committed
return $form;
Angie Byron
committed
}
Dries Buytaert
committed
* {@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();
Angie Byron
committed
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()]);
}
drupal_set_message($message);
Angie Byron
committed
if ($entity->id()) {
$entity_type = $entity->getEntityTypeId();
$form_state->setRedirect(
"entity.$entity_type.edit_form",
[$entity_type => $entity->id()]
);
}
else {
// Error on save.
drupal_set_message(t('The entity could not be saved.'), 'error');
$form_state->setRebuild();
}
Angie Byron
committed
}
catch (\Exception $e) {
\Drupal::state()->set('entity_test.form.save.exception', get_class($e) . ': ' . $e->getMessage());
Angie Byron
committed
}
}
Alex Pott
committed