Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Entity / ContentEntityForm.php
1 <?php
2
3 namespace Drupal\Core\Entity;
4
5 use Drupal\Component\Datetime\TimeInterface;
6 use Drupal\Core\Entity\Display\EntityFormDisplayInterface;
7 use Drupal\Core\Entity\Entity\EntityFormDisplay;
8 use Drupal\Core\Form\FormStateInterface;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10
11 /**
12  * Entity form variant for content entity types.
13  *
14  * @see \Drupal\Core\ContentEntityBase
15  */
16 class ContentEntityForm extends EntityForm implements ContentEntityFormInterface {
17
18   /**
19    * The entity manager.
20    *
21    * @var \Drupal\Core\Entity\EntityManagerInterface
22    */
23   protected $entityManager;
24
25   /**
26    * The entity being used by this form.
27    *
28    * @var \Drupal\Core\Entity\ContentEntityInterface|\Drupal\Core\Entity\RevisionLogInterface
29    */
30   protected $entity;
31
32   /**
33    * The entity type bundle info service.
34    *
35    * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
36    */
37   protected $entityTypeBundleInfo;
38
39   /**
40    * The time service.
41    *
42    * @var \Drupal\Component\Datetime\TimeInterface
43    */
44   protected $time;
45
46   /**
47    * Constructs a ContentEntityForm object.
48    *
49    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
50    *   The entity manager.
51    * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
52    *   The entity type bundle service.
53    * @param \Drupal\Component\Datetime\TimeInterface $time
54    *   The time service.
55    */
56   public function __construct(EntityManagerInterface $entity_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
57     $this->entityManager = $entity_manager;
58
59     $this->entityTypeBundleInfo = $entity_type_bundle_info ?: \Drupal::service('entity_type.bundle.info');
60     $this->time = $time ?: \Drupal::service('datetime.time');
61   }
62
63   /**
64    * {@inheritdoc}
65    */
66   public static function create(ContainerInterface $container) {
67     return new static(
68       $container->get('entity.manager'),
69       $container->get('entity_type.bundle.info'),
70       $container->get('datetime.time')
71     );
72   }
73
74   /**
75    * {@inheritdoc}
76    */
77   protected function prepareEntity() {
78     parent::prepareEntity();
79
80     // Hide the current revision log message in UI.
81     if ($this->showRevisionUi() && !$this->entity->isNew() && $this->entity instanceof RevisionLogInterface) {
82       $this->entity->setRevisionLogMessage(NULL);
83     }
84   }
85
86   /**
87    * Returns the bundle entity of the entity, or NULL if there is none.
88    *
89    * @return \Drupal\Core\Entity\EntityInterface|null
90    *   The bundle entity.
91    */
92   protected function getBundleEntity() {
93     if ($bundle_entity_type = $this->entity->getEntityType()->getBundleEntityType()) {
94       return $this->entityTypeManager->getStorage($bundle_entity_type)->load($this->entity->bundle());
95     }
96     return NULL;
97   }
98
99   /**
100    * {@inheritdoc}
101    */
102   public function form(array $form, FormStateInterface $form_state) {
103
104     if ($this->showRevisionUi()) {
105       // Advanced tab must be the first, because other fields rely on that.
106       if (!isset($form['advanced'])) {
107         $form['advanced'] = [
108           '#type' => 'vertical_tabs',
109           '#weight' => 99,
110         ];
111       }
112     }
113
114     $form = parent::form($form, $form_state);
115
116     // Content entity forms do not use the parent's #after_build callback
117     // because they only need to rebuild the entity in the validation and the
118     // submit handler because Field API uses its own #after_build callback for
119     // its widgets.
120     unset($form['#after_build']);
121
122     $this->getFormDisplay($form_state)->buildForm($this->entity, $form, $form_state);
123     // Allow modules to act before and after form language is updated.
124     $form['#entity_builders']['update_form_langcode'] = '::updateFormLangcode';
125
126     if ($this->showRevisionUi()) {
127       $this->addRevisionableFormFields($form);
128     }
129
130     return $form;
131   }
132
133   /**
134    * {@inheritdoc}
135    */
136   public function submitForm(array &$form, FormStateInterface $form_state) {
137     parent::submitForm($form, $form_state);
138     // Update the changed timestamp of the entity.
139     $this->updateChangedTime($this->entity);
140   }
141
142   /**
143    * {@inheritdoc}
144    */
145   public function buildEntity(array $form, FormStateInterface $form_state) {
146     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
147     $entity = parent::buildEntity($form, $form_state);
148
149     // Mark the entity as requiring validation.
150     $entity->setValidationRequired(!$form_state->getTemporaryValue('entity_validated'));
151
152     // Save as a new revision if requested to do so.
153     if ($this->showRevisionUi() && !$form_state->isValueEmpty('revision')) {
154       $entity->setNewRevision();
155       if ($entity instanceof RevisionLogInterface) {
156         // If a new revision is created, save the current user as
157         // revision author.
158         $entity->setRevisionUserId($this->currentUser()->id());
159         $entity->setRevisionCreationTime($this->time->getRequestTime());
160       }
161     }
162
163     return $entity;
164   }
165
166   /**
167    * {@inheritdoc}
168    *
169    * Button-level validation handlers are highly discouraged for entity forms,
170    * as they will prevent entity validation from running. If the entity is going
171    * to be saved during the form submission, this method should be manually
172    * invoked from the button-level validation handler, otherwise an exception
173    * will be thrown.
174    */
175   public function validateForm(array &$form, FormStateInterface $form_state) {
176     parent::validateForm($form, $form_state);
177     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
178     $entity = $this->buildEntity($form, $form_state);
179
180     $violations = $entity->validate();
181
182     // Remove violations of inaccessible fields and not edited fields.
183     $violations
184       ->filterByFieldAccess($this->currentUser())
185       ->filterByFields(array_diff(array_keys($entity->getFieldDefinitions()), $this->getEditedFieldNames($form_state)));
186
187     $this->flagViolations($violations, $form, $form_state);
188
189     // The entity was validated.
190     $entity->setValidationRequired(FALSE);
191     $form_state->setTemporaryValue('entity_validated', TRUE);
192
193     return $entity;
194   }
195
196   /**
197    * Gets the names of all fields edited in the form.
198    *
199    * If the entity form customly adds some fields to the form (i.e. without
200    * using the form display), it needs to add its fields here and override
201    * flagViolations() for displaying the violations.
202    *
203    * @param \Drupal\Core\Form\FormStateInterface $form_state
204    *   The current state of the form.
205    *
206    * @return string[]
207    *   An array of field names.
208    */
209   protected function getEditedFieldNames(FormStateInterface $form_state) {
210     return array_keys($this->getFormDisplay($form_state)->getComponents());
211   }
212
213   /**
214    * Flags violations for the current form.
215    *
216    * If the entity form customly adds some fields to the form (i.e. without
217    * using the form display), it needs to add its fields to array returned by
218    * getEditedFieldNames() and overwrite this method in order to show any
219    * violations for those fields; e.g.:
220    * @code
221    * foreach ($violations->getByField('name') as $violation) {
222    *   $form_state->setErrorByName('name', $violation->getMessage());
223    * }
224    * parent::flagViolations($violations, $form, $form_state);
225    * @endcode
226    *
227    * @param \Drupal\Core\Entity\EntityConstraintViolationListInterface $violations
228    *   The violations to flag.
229    * @param array $form
230    *   A nested array of form elements comprising the form.
231    * @param \Drupal\Core\Form\FormStateInterface $form_state
232    *   The current state of the form.
233    */
234   protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
235     // Flag entity level violations.
236     foreach ($violations->getEntityViolations() as $violation) {
237       /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */
238       $form_state->setErrorByName('', $violation->getMessage());
239     }
240     // Let the form display flag violations of its fields.
241     $this->getFormDisplay($form_state)->flagWidgetsErrorsFromViolations($violations, $form, $form_state);
242   }
243
244   /**
245    * Initializes the form state and the entity before the first form build.
246    *
247    * @param \Drupal\Core\Form\FormStateInterface $form_state
248    *   The current state of the form.
249    */
250   protected function init(FormStateInterface $form_state) {
251     // Ensure we act on the translation object corresponding to the current form
252     // language.
253     $this->initFormLangcodes($form_state);
254     $langcode = $this->getFormLangcode($form_state);
255     $this->entity = $this->entity->hasTranslation($langcode) ? $this->entity->getTranslation($langcode) : $this->entity->addTranslation($langcode);
256
257     $form_display = EntityFormDisplay::collectRenderDisplay($this->entity, $this->getOperation());
258     $this->setFormDisplay($form_display, $form_state);
259
260     parent::init($form_state);
261   }
262
263   /**
264    * Initializes form language code values.
265    *
266    * @param \Drupal\Core\Form\FormStateInterface $form_state
267    *   The current state of the form.
268    */
269   protected function initFormLangcodes(FormStateInterface $form_state) {
270     // Store the entity default language to allow checking whether the form is
271     // dealing with the original entity or a translation.
272     if (!$form_state->has('entity_default_langcode')) {
273       $form_state->set('entity_default_langcode', $this->entity->getUntranslated()->language()->getId());
274     }
275     // This value might have been explicitly populated to work with a particular
276     // entity translation. If not we fall back to the most proper language based
277     // on contextual information.
278     if (!$form_state->has('langcode')) {
279       // Imply a 'view' operation to ensure users edit entities in the same
280       // language they are displayed. This allows to keep contextual editing
281       // working also for multilingual entities.
282       $form_state->set('langcode', $this->entityManager->getTranslationFromContext($this->entity)->language()->getId());
283     }
284   }
285
286   /**
287    * {@inheritdoc}
288    */
289   public function getFormLangcode(FormStateInterface $form_state) {
290     $this->initFormLangcodes($form_state);
291     return $form_state->get('langcode');
292   }
293
294   /**
295    * {@inheritdoc}
296    */
297   public function isDefaultFormLangcode(FormStateInterface $form_state) {
298     $this->initFormLangcodes($form_state);
299     return $form_state->get('langcode') == $form_state->get('entity_default_langcode');
300   }
301
302   /**
303    * {@inheritdoc}
304    */
305   protected function copyFormValuesToEntity(EntityInterface $entity, array $form, FormStateInterface $form_state) {
306     // First, extract values from widgets.
307     $extracted = $this->getFormDisplay($form_state)->extractFormValues($entity, $form, $form_state);
308
309     // Then extract the values of fields that are not rendered through widgets,
310     // by simply copying from top-level form values. This leaves the fields
311     // that are not being edited within this form untouched.
312     foreach ($form_state->getValues() as $name => $values) {
313       if ($entity->hasField($name) && !isset($extracted[$name])) {
314         $entity->set($name, $values);
315       }
316     }
317   }
318
319   /**
320    * {@inheritdoc}
321    */
322   public function getFormDisplay(FormStateInterface $form_state) {
323     return $form_state->get('form_display');
324   }
325
326   /**
327    * {@inheritdoc}
328    */
329   public function setFormDisplay(EntityFormDisplayInterface $form_display, FormStateInterface $form_state) {
330     $form_state->set('form_display', $form_display);
331     return $this;
332   }
333
334   /**
335    * Updates the form language to reflect any change to the entity language.
336    *
337    * There are use cases for modules to act both before and after form language
338    * being updated, thus the update is performed through an entity builder
339    * callback, which allows to support both cases.
340    *
341    * @param string $entity_type_id
342    *   The entity type identifier.
343    * @param \Drupal\Core\Entity\EntityInterface $entity
344    *   The entity updated with the submitted values.
345    * @param array $form
346    *   The complete form array.
347    * @param \Drupal\Core\Form\FormStateInterface $form_state
348    *   The current state of the form.
349    *
350    * @see \Drupal\Core\Entity\ContentEntityForm::form()
351    */
352   public function updateFormLangcode($entity_type_id, EntityInterface $entity, array $form, FormStateInterface $form_state) {
353     $langcode = $entity->language()->getId();
354     $form_state->set('langcode', $langcode);
355
356     // If this is the original entity language, also update the default
357     // langcode.
358     if ($langcode == $entity->getUntranslated()->language()->getId()) {
359       $form_state->set('entity_default_langcode', $langcode);
360     }
361   }
362
363   /**
364    * Updates the changed time of the entity.
365    *
366    * Applies only if the entity implements the EntityChangedInterface.
367    *
368    * @param \Drupal\Core\Entity\EntityInterface $entity
369    *   The entity updated with the submitted values.
370    */
371   public function updateChangedTime(EntityInterface $entity) {
372     if ($entity instanceof EntityChangedInterface) {
373       $entity->setChangedTime($this->time->getRequestTime());
374     }
375   }
376
377   /**
378    * Add revision form fields if the entity enabled the UI.
379    *
380    * @param array $form
381    *   An associative array containing the structure of the form.
382    */
383   protected function addRevisionableFormFields(array &$form) {
384     $entity_type = $this->entity->getEntityType();
385
386     $new_revision_default = $this->getNewRevisionDefault();
387
388     // Add a log field if the "Create new revision" option is checked, or if the
389     // current user has the ability to check that option.
390     $form['revision_information'] = [
391       '#type' => 'details',
392       '#title' => $this->t('Revision information'),
393       // Open by default when "Create new revision" is checked.
394       '#open' => $new_revision_default,
395       '#group' => 'advanced',
396       '#weight' => 20,
397       '#access' => $new_revision_default || $this->entity->get($entity_type->getKey('revision'))->access('update'),
398       '#optional' => TRUE,
399       '#attributes' => [
400         'class' => ['entity-content-form-revision-information'],
401       ],
402       '#attached' => [
403         'library' => ['core/drupal.entity-form'],
404       ],
405     ];
406
407     $form['revision'] = [
408       '#type' => 'checkbox',
409       '#title' => $this->t('Create new revision'),
410       '#default_value' => $new_revision_default,
411       '#access' => !$this->entity->isNew() && $this->entity->get($entity_type->getKey('revision'))->access('update'),
412       '#group' => 'revision_information',
413     ];
414
415     if (isset($form['revision_log'])) {
416       $form['revision_log'] += [
417         '#group' => 'revision_information',
418         '#states' => [
419           'visible' => [
420             ':input[name="revision"]' => ['checked' => TRUE],
421           ],
422         ],
423       ];
424     }
425   }
426
427   /**
428    * Should new revisions created on default.
429    *
430    * @return bool
431    *   New revision on default.
432    */
433   protected function getNewRevisionDefault() {
434     $new_revision_default = FALSE;
435     $bundle_entity = $this->getBundleEntity();
436     if ($bundle_entity instanceof RevisionableEntityBundleInterface) {
437       // Always use the default revision setting.
438       $new_revision_default = $bundle_entity->shouldCreateNewRevision();
439     }
440     return $new_revision_default;
441   }
442
443   /**
444    * Checks whether the revision form fields should be added to the form.
445    *
446    * @return bool
447    *   TRUE if the form field should be added, FALSE otherwise.
448    */
449   protected function showRevisionUi() {
450     return $this->entity->getEntityType()->showRevisionUi();
451   }
452
453 }