QuickEditController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. namespace Drupal\quickedit;
  3. use Drupal\Core\Controller\ControllerBase;
  4. use Drupal\Core\Form\FormState;
  5. use Drupal\Core\Render\RendererInterface;
  6. use Drupal\Core\TempStore\PrivateTempStoreFactory;
  7. use Symfony\Component\DependencyInjection\ContainerInterface;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  11. use Drupal\Core\Ajax\AjaxResponse;
  12. use Drupal\Core\Entity\EntityInterface;
  13. use Drupal\quickedit\Ajax\FieldFormCommand;
  14. use Drupal\quickedit\Ajax\FieldFormSavedCommand;
  15. use Drupal\quickedit\Ajax\FieldFormValidationErrorsCommand;
  16. use Drupal\quickedit\Ajax\EntitySavedCommand;
  17. /**
  18. * Returns responses for Quick Edit module routes.
  19. */
  20. class QuickEditController extends ControllerBase {
  21. /**
  22. * The PrivateTempStore factory.
  23. *
  24. * @var \Drupal\Core\TempStore\PrivateTempStoreFactory
  25. */
  26. protected $tempStoreFactory;
  27. /**
  28. * The in-place editing metadata generator.
  29. *
  30. * @var \Drupal\quickedit\MetadataGeneratorInterface
  31. */
  32. protected $metadataGenerator;
  33. /**
  34. * The in-place editor selector.
  35. *
  36. * @var \Drupal\quickedit\EditorSelectorInterface
  37. */
  38. protected $editorSelector;
  39. /**
  40. * The renderer.
  41. *
  42. * @var \Drupal\Core\Render\RendererInterface
  43. */
  44. protected $renderer;
  45. /**
  46. * Constructs a new QuickEditController.
  47. *
  48. * @param \Drupal\Core\TempStore\PrivateTempStoreFactory $temp_store_factory
  49. * The PrivateTempStore factory.
  50. * @param \Drupal\quickedit\MetadataGeneratorInterface $metadata_generator
  51. * The in-place editing metadata generator.
  52. * @param \Drupal\quickedit\EditorSelectorInterface $editor_selector
  53. * The in-place editor selector.
  54. * @param \Drupal\Core\Render\RendererInterface $renderer
  55. * The renderer.
  56. */
  57. public function __construct(PrivateTempStoreFactory $temp_store_factory, MetadataGeneratorInterface $metadata_generator, EditorSelectorInterface $editor_selector, RendererInterface $renderer) {
  58. $this->tempStoreFactory = $temp_store_factory;
  59. $this->metadataGenerator = $metadata_generator;
  60. $this->editorSelector = $editor_selector;
  61. $this->renderer = $renderer;
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public static function create(ContainerInterface $container) {
  67. return new static(
  68. $container->get('tempstore.private'),
  69. $container->get('quickedit.metadata.generator'),
  70. $container->get('quickedit.editor.selector'),
  71. $container->get('renderer')
  72. );
  73. }
  74. /**
  75. * Returns the metadata for a set of fields.
  76. *
  77. * Given a list of field quick edit IDs as POST parameters, run access checks
  78. * on the entity and field level to determine whether the current user may
  79. * edit them. Also retrieves other metadata.
  80. *
  81. * @return \Symfony\Component\HttpFoundation\JsonResponse
  82. * The JSON response.
  83. */
  84. public function metadata(Request $request) {
  85. $fields = $request->request->get('fields');
  86. if (!isset($fields)) {
  87. throw new NotFoundHttpException();
  88. }
  89. $entities = $request->request->get('entities');
  90. $metadata = [];
  91. foreach ($fields as $field) {
  92. list($entity_type, $entity_id, $field_name, $langcode, $view_mode) = explode('/', $field);
  93. // Load the entity.
  94. if (!$entity_type || !$this->entityManager()->getDefinition($entity_type)) {
  95. throw new NotFoundHttpException();
  96. }
  97. $entity = $this->entityManager()->getStorage($entity_type)->load($entity_id);
  98. if (!$entity) {
  99. throw new NotFoundHttpException();
  100. }
  101. // Validate the field name and language.
  102. if (!$field_name || !$entity->hasField($field_name)) {
  103. throw new NotFoundHttpException();
  104. }
  105. if (!$langcode || !$entity->hasTranslation($langcode)) {
  106. throw new NotFoundHttpException();
  107. }
  108. $entity = $entity->getTranslation($langcode);
  109. // If the entity information for this field is requested, include it.
  110. $entity_id = $entity->getEntityTypeId() . '/' . $entity_id;
  111. if (is_array($entities) && in_array($entity_id, $entities) && !isset($metadata[$entity_id])) {
  112. $metadata[$entity_id] = $this->metadataGenerator->generateEntityMetadata($entity);
  113. }
  114. $metadata[$field] = $this->metadataGenerator->generateFieldMetadata($entity->get($field_name), $view_mode);
  115. }
  116. return new JsonResponse($metadata);
  117. }
  118. /**
  119. * Returns AJAX commands to load in-place editors' attachments.
  120. *
  121. * Given a list of in-place editor IDs as POST parameters, render AJAX
  122. * commands to load those in-place editors.
  123. *
  124. * @return \Drupal\Core\Ajax\AjaxResponse
  125. * The Ajax response.
  126. */
  127. public function attachments(Request $request) {
  128. $response = new AjaxResponse();
  129. $editors = $request->request->get('editors');
  130. if (!isset($editors)) {
  131. throw new NotFoundHttpException();
  132. }
  133. $response->setAttachments($this->editorSelector->getEditorAttachments($editors));
  134. return $response;
  135. }
  136. /**
  137. * Returns a single field edit form as an Ajax response.
  138. *
  139. * @param \Drupal\Core\Entity\EntityInterface $entity
  140. * The entity being edited.
  141. * @param string $field_name
  142. * The name of the field that is being edited.
  143. * @param string $langcode
  144. * The name of the language for which the field is being edited.
  145. * @param string $view_mode_id
  146. * The view mode the field should be rerendered in.
  147. * @param \Symfony\Component\HttpFoundation\Request $request
  148. * The current request object containing the search string.
  149. *
  150. * @return \Drupal\Core\Ajax\AjaxResponse
  151. * The Ajax response.
  152. */
  153. public function fieldForm(EntityInterface $entity, $field_name, $langcode, $view_mode_id, Request $request) {
  154. $response = new AjaxResponse();
  155. // Replace entity with PrivateTempStore copy if available and not resetting,
  156. // init PrivateTempStore copy otherwise.
  157. $tempstore_entity = $this->tempStoreFactory->get('quickedit')->get($entity->uuid());
  158. if ($tempstore_entity && $request->request->get('reset') !== 'true') {
  159. $entity = $tempstore_entity;
  160. }
  161. else {
  162. $this->tempStoreFactory->get('quickedit')->set($entity->uuid(), $entity);
  163. }
  164. $form_state = (new FormState())
  165. ->set('langcode', $langcode)
  166. ->disableRedirect()
  167. ->addBuildInfo('args', [$entity, $field_name]);
  168. $form = $this->formBuilder()->buildForm('Drupal\quickedit\Form\QuickEditFieldForm', $form_state);
  169. if ($form_state->isExecuted()) {
  170. // The form submission saved the entity in PrivateTempStore. Return the
  171. // updated view of the field from the PrivateTempStore copy.
  172. $entity = $this->tempStoreFactory->get('quickedit')->get($entity->uuid());
  173. // Closure to render the field given a view mode.
  174. $render_field_in_view_mode = function ($view_mode_id) use ($entity, $field_name, $langcode) {
  175. return $this->renderField($entity, $field_name, $langcode, $view_mode_id);
  176. };
  177. // Re-render the updated field.
  178. $output = $render_field_in_view_mode($view_mode_id);
  179. // Re-render the updated field for other view modes (i.e. for other
  180. // instances of the same logical field on the user's page).
  181. $other_view_mode_ids = $request->request->get('other_view_modes') ?: [];
  182. $other_view_modes = array_map($render_field_in_view_mode, array_combine($other_view_mode_ids, $other_view_mode_ids));
  183. $response->addCommand(new FieldFormSavedCommand($output, $other_view_modes));
  184. }
  185. else {
  186. $output = $this->renderer->renderRoot($form);
  187. // When working with a hidden form, we don't want its CSS/JS to be loaded.
  188. if ($request->request->get('nocssjs') !== 'true') {
  189. $response->setAttachments($form['#attached']);
  190. }
  191. $response->addCommand(new FieldFormCommand($output));
  192. $errors = $form_state->getErrors();
  193. if (count($errors)) {
  194. $status_messages = [
  195. '#type' => 'status_messages'
  196. ];
  197. $response->addCommand(new FieldFormValidationErrorsCommand($this->renderer->renderRoot($status_messages)));
  198. }
  199. }
  200. return $response;
  201. }
  202. /**
  203. * Renders a field.
  204. *
  205. * If the view mode ID is not an Entity Display view mode ID, then the field
  206. * was rendered using a custom render pipeline (not the Entity/Field API
  207. * render pipeline).
  208. *
  209. * An example could be Views' render pipeline. In that case, the view mode ID
  210. * would probably contain the View's ID, display and the row index.
  211. *
  212. * @param \Drupal\Core\Entity\EntityInterface $entity
  213. * The entity being edited.
  214. * @param string $field_name
  215. * The name of the field that is being edited.
  216. * @param string $langcode
  217. * The name of the language for which the field is being edited.
  218. * @param string $view_mode_id
  219. * The view mode the field should be rerendered in. Either an Entity Display
  220. * view mode ID, or a custom one. See hook_quickedit_render_field().
  221. *
  222. * @return \Drupal\Component\Render\MarkupInterface
  223. * Rendered HTML.
  224. *
  225. * @see hook_quickedit_render_field()
  226. */
  227. protected function renderField(EntityInterface $entity, $field_name, $langcode, $view_mode_id) {
  228. $entity_view_mode_ids = array_keys($this->entityManager()->getViewModes($entity->getEntityTypeId()));
  229. if (in_array($view_mode_id, $entity_view_mode_ids)) {
  230. $entity = \Drupal::entityManager()->getTranslationFromContext($entity, $langcode);
  231. $output = $entity->get($field_name)->view($view_mode_id);
  232. }
  233. else {
  234. // Each part of a custom (non-Entity Display) view mode ID is separated
  235. // by a dash; the first part must be the module name.
  236. $mode_id_parts = explode('-', $view_mode_id, 2);
  237. $module = reset($mode_id_parts);
  238. $args = [$entity, $field_name, $view_mode_id, $langcode];
  239. $output = $this->moduleHandler()->invoke($module, 'quickedit_render_field', $args);
  240. }
  241. return $this->renderer->renderRoot($output);
  242. }
  243. /**
  244. * Saves an entity into the database, from PrivateTempStore.
  245. *
  246. * @param \Drupal\Core\Entity\EntityInterface $entity
  247. * The entity being edited.
  248. *
  249. * @return \Drupal\Core\Ajax\AjaxResponse
  250. * The Ajax response.
  251. */
  252. public function entitySave(EntityInterface $entity) {
  253. // Take the entity from PrivateTempStore and save in entity storage.
  254. // fieldForm() ensures that the PrivateTempStore copy exists ahead.
  255. $tempstore = $this->tempStoreFactory->get('quickedit');
  256. $tempstore->get($entity->uuid())->save();
  257. $tempstore->delete($entity->uuid());
  258. // Return information about the entity that allows a front end application
  259. // to identify it.
  260. $output = [
  261. 'entity_type' => $entity->getEntityTypeId(),
  262. 'entity_id' => $entity->id()
  263. ];
  264. // Respond to client that the entity was saved properly.
  265. $response = new AjaxResponse();
  266. $response->addCommand(new EntitySavedCommand($output));
  267. return $response;
  268. }
  269. }