3 namespace Drupal\Core\Entity;
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;
12 * Entity form variant for content entity types.
14 * @see \Drupal\Core\ContentEntityBase
16 class ContentEntityForm extends EntityForm implements ContentEntityFormInterface {
21 * @var \Drupal\Core\Entity\EntityManagerInterface
23 protected $entityManager;
26 * The entity being used by this form.
28 * @var \Drupal\Core\Entity\ContentEntityInterface|\Drupal\Core\Entity\RevisionLogInterface
33 * The entity type bundle info service.
35 * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
37 protected $entityTypeBundleInfo;
42 * @var \Drupal\Component\Datetime\TimeInterface
47 * Constructs a ContentEntityForm object.
49 * @param \Drupal\Core\Entity\EntityManagerInterface $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
56 public function __construct(EntityManagerInterface $entity_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
57 $this->entityManager = $entity_manager;
59 $this->entityTypeBundleInfo = $entity_type_bundle_info ?: \Drupal::service('entity_type.bundle.info');
60 $this->time = $time ?: \Drupal::service('datetime.time');
66 public static function create(ContainerInterface $container) {
68 $container->get('entity.manager'),
69 $container->get('entity_type.bundle.info'),
70 $container->get('datetime.time')
77 protected function prepareEntity() {
78 parent::prepareEntity();
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);
87 * Returns the bundle entity of the entity, or NULL if there is none.
89 * @return \Drupal\Core\Entity\EntityInterface|null
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());
102 public function form(array $form, FormStateInterface $form_state) {
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',
114 $form = parent::form($form, $form_state);
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
120 unset($form['#after_build']);
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';
126 if ($this->showRevisionUi()) {
127 $this->addRevisionableFormFields($form);
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);
145 public function buildEntity(array $form, FormStateInterface $form_state) {
146 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
147 $entity = parent::buildEntity($form, $form_state);
149 // Mark the entity as requiring validation.
150 $entity->setValidationRequired(!$form_state->getTemporaryValue('entity_validated'));
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
158 $entity->setRevisionUserId($this->currentUser()->id());
159 $entity->setRevisionCreationTime($this->time->getRequestTime());
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
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);
180 $violations = $entity->validate();
182 // Remove violations of inaccessible fields and not edited fields.
184 ->filterByFieldAccess($this->currentUser())
185 ->filterByFields(array_diff(array_keys($entity->getFieldDefinitions()), $this->getEditedFieldNames($form_state)));
187 $this->flagViolations($violations, $form, $form_state);
189 // The entity was validated.
190 $entity->setValidationRequired(FALSE);
191 $form_state->setTemporaryValue('entity_validated', TRUE);
197 * Gets the names of all fields edited in the form.
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.
203 * @param \Drupal\Core\Form\FormStateInterface $form_state
204 * The current state of the form.
207 * An array of field names.
209 protected function getEditedFieldNames(FormStateInterface $form_state) {
210 return array_keys($this->getFormDisplay($form_state)->getComponents());
214 * Flags violations for the current form.
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.:
221 * foreach ($violations->getByField('name') as $violation) {
222 * $form_state->setErrorByName('name', $violation->getMessage());
224 * parent::flagViolations($violations, $form, $form_state);
227 * @param \Drupal\Core\Entity\EntityConstraintViolationListInterface $violations
228 * The violations to flag.
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.
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());
240 // Let the form display flag violations of its fields.
241 $this->getFormDisplay($form_state)->flagWidgetsErrorsFromViolations($violations, $form, $form_state);
245 * Initializes the form state and the entity before the first form build.
247 * @param \Drupal\Core\Form\FormStateInterface $form_state
248 * The current state of the form.
250 protected function init(FormStateInterface $form_state) {
251 // Ensure we act on the translation object corresponding to the current form
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);
257 $form_display = EntityFormDisplay::collectRenderDisplay($this->entity, $this->getOperation());
258 $this->setFormDisplay($form_display, $form_state);
260 parent::init($form_state);
264 * Initializes form language code values.
266 * @param \Drupal\Core\Form\FormStateInterface $form_state
267 * The current state of the form.
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());
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());
289 public function getFormLangcode(FormStateInterface $form_state) {
290 $this->initFormLangcodes($form_state);
291 return $form_state->get('langcode');
297 public function isDefaultFormLangcode(FormStateInterface $form_state) {
298 $this->initFormLangcodes($form_state);
299 return $form_state->get('langcode') == $form_state->get('entity_default_langcode');
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);
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);
322 public function getFormDisplay(FormStateInterface $form_state) {
323 return $form_state->get('form_display');
329 public function setFormDisplay(EntityFormDisplayInterface $form_display, FormStateInterface $form_state) {
330 $form_state->set('form_display', $form_display);
335 * Updates the form language to reflect any change to the entity language.
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.
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.
346 * The complete form array.
347 * @param \Drupal\Core\Form\FormStateInterface $form_state
348 * The current state of the form.
350 * @see \Drupal\Core\Entity\ContentEntityForm::form()
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);
356 // If this is the original entity language, also update the default
358 if ($langcode == $entity->getUntranslated()->language()->getId()) {
359 $form_state->set('entity_default_langcode', $langcode);
364 * Updates the changed time of the entity.
366 * Applies only if the entity implements the EntityChangedInterface.
368 * @param \Drupal\Core\Entity\EntityInterface $entity
369 * The entity updated with the submitted values.
371 public function updateChangedTime(EntityInterface $entity) {
372 if ($entity instanceof EntityChangedInterface) {
373 $entity->setChangedTime($this->time->getRequestTime());
378 * Add revision form fields if the entity enabled the UI.
381 * An associative array containing the structure of the form.
383 protected function addRevisionableFormFields(array &$form) {
384 $entity_type = $this->entity->getEntityType();
386 $new_revision_default = $this->getNewRevisionDefault();
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',
397 '#access' => $new_revision_default || $this->entity->get($entity_type->getKey('revision'))->access('update'),
400 'class' => ['entity-content-form-revision-information'],
403 'library' => ['core/drupal.entity-form'],
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',
415 if (isset($form['revision_log'])) {
416 $form['revision_log'] += [
417 '#group' => 'revision_information',
420 ':input[name="revision"]' => ['checked' => TRUE],
428 * Should new revisions created on default.
431 * New revision on default.
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();
440 return $new_revision_default;
444 * Checks whether the revision form fields should be added to the form.
447 * TRUE if the form field should be added, FALSE otherwise.
449 protected function showRevisionUi() {
450 return $this->entity->getEntityType()->showRevisionUi();