72a8a19643a0368fa3aea6b5eb9af160529a61f0
[yaffs-website] / web / core / modules / field_ui / src / Form / EntityDisplayModeFormBase.php
1 <?php
2
3 namespace Drupal\field_ui\Form;
4
5 use Drupal\Core\Entity\EntityForm;
6 use Drupal\Core\Form\FormStateInterface;
7
8 /**
9  * Provides the generic base class for entity display mode forms.
10  */
11 abstract class EntityDisplayModeFormBase extends EntityForm {
12
13   /**
14    * The entity type definition.
15    *
16    * @var \Drupal\Core\Entity\EntityTypeInterface
17    */
18   protected $entityType;
19
20   /**
21    * {@inheritdoc}
22    */
23   protected function init(FormStateInterface $form_state) {
24     parent::init($form_state);
25     $this->entityType = $this->entityTypeManager->getDefinition($this->entity->getEntityTypeId());
26   }
27
28   /**
29    * {@inheritdoc}
30    */
31   public function form(array $form, FormStateInterface $form_state) {
32     $form['label'] = [
33       '#type' => 'textfield',
34       '#title' => $this->t('Name'),
35       '#maxlength' => 100,
36       '#default_value' => $this->entity->label(),
37     ];
38
39     $form['id'] = [
40       '#type' => 'machine_name',
41       '#description' => $this->t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
42       '#disabled' => !$this->entity->isNew(),
43       '#default_value' => $this->entity->id(),
44       '#field_prefix' => $this->entity->isNew() ? $this->entity->getTargetType() . '.' : '',
45       '#machine_name' => [
46         'exists' => [$this, 'exists'],
47         'replace_pattern' => '[^a-z0-9_.]+',
48       ],
49     ];
50
51     return $form;
52   }
53
54   /**
55    * Determines if the display mode already exists.
56    *
57    * @param string|int $entity_id
58    *   The entity ID.
59    * @param array $element
60    *   The form element.
61    *
62    * @return bool
63    *   TRUE if the display mode exists, FALSE otherwise.
64    */
65   public function exists($entity_id, array $element) {
66     // Do not allow to add internal 'default' view mode.
67     if ($entity_id == 'default') {
68       return TRUE;
69     }
70     return (bool) $this->entityTypeManager
71       ->getStorage($this->entity->getEntityTypeId())
72       ->getQuery()
73       ->condition('id', $element['#field_prefix'] . $entity_id)
74       ->execute();
75   }
76
77   /**
78    * {@inheritdoc}
79    */
80   public function save(array $form, FormStateInterface $form_state) {
81     drupal_set_message($this->t('Saved the %label @entity-type.', ['%label' => $this->entity->label(), '@entity-type' => $this->entityType->getLowercaseLabel()]));
82     $this->entity->save();
83     \Drupal::entityManager()->clearCachedFieldDefinitions();
84     $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
85   }
86
87 }