ContentEntityForm.php 16 KB

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