3 namespace Drupal\quickedit;
5 use Drupal\Core\Controller\ControllerBase;
6 use Drupal\Core\Form\FormState;
7 use Drupal\Core\Render\RendererInterface;
8 use Drupal\user\PrivateTempStoreFactory;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10 use Symfony\Component\HttpFoundation\JsonResponse;
11 use Symfony\Component\HttpFoundation\Request;
12 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
13 use Drupal\Core\Ajax\AjaxResponse;
14 use Drupal\Core\Entity\EntityInterface;
15 use Drupal\quickedit\Ajax\FieldFormCommand;
16 use Drupal\quickedit\Ajax\FieldFormSavedCommand;
17 use Drupal\quickedit\Ajax\FieldFormValidationErrorsCommand;
18 use Drupal\quickedit\Ajax\EntitySavedCommand;
21 * Returns responses for Quick Edit module routes.
23 class QuickEditController extends ControllerBase {
26 * The PrivateTempStore factory.
28 * @var \Drupal\user\PrivateTempStoreFactory
30 protected $tempStoreFactory;
33 * The in-place editing metadata generator.
35 * @var \Drupal\quickedit\MetadataGeneratorInterface
37 protected $metadataGenerator;
40 * The in-place editor selector.
42 * @var \Drupal\quickedit\EditorSelectorInterface
44 protected $editorSelector;
49 * @var \Drupal\Core\Render\RendererInterface
54 * Constructs a new QuickEditController.
56 * @param \Drupal\user\PrivateTempStoreFactory $temp_store_factory
57 * The PrivateTempStore factory.
58 * @param \Drupal\quickedit\MetadataGeneratorInterface $metadata_generator
59 * The in-place editing metadata generator.
60 * @param \Drupal\quickedit\EditorSelectorInterface $editor_selector
61 * The in-place editor selector.
62 * @param \Drupal\Core\Render\RendererInterface $renderer
65 public function __construct(PrivateTempStoreFactory $temp_store_factory, MetadataGeneratorInterface $metadata_generator, EditorSelectorInterface $editor_selector, RendererInterface $renderer) {
66 $this->tempStoreFactory = $temp_store_factory;
67 $this->metadataGenerator = $metadata_generator;
68 $this->editorSelector = $editor_selector;
69 $this->renderer = $renderer;
75 public static function create(ContainerInterface $container) {
77 $container->get('user.private_tempstore'),
78 $container->get('quickedit.metadata.generator'),
79 $container->get('quickedit.editor.selector'),
80 $container->get('renderer')
85 * Returns the metadata for a set of fields.
87 * Given a list of field quick edit IDs as POST parameters, run access checks
88 * on the entity and field level to determine whether the current user may
89 * edit them. Also retrieves other metadata.
91 * @return \Symfony\Component\HttpFoundation\JsonResponse
94 public function metadata(Request $request) {
95 $fields = $request->request->get('fields');
96 if (!isset($fields)) {
97 throw new NotFoundHttpException();
99 $entities = $request->request->get('entities');
102 foreach ($fields as $field) {
103 list($entity_type, $entity_id, $field_name, $langcode, $view_mode) = explode('/', $field);
106 if (!$entity_type || !$this->entityManager()->getDefinition($entity_type)) {
107 throw new NotFoundHttpException();
109 $entity = $this->entityManager()->getStorage($entity_type)->load($entity_id);
111 throw new NotFoundHttpException();
114 // Validate the field name and language.
115 if (!$field_name || !$entity->hasField($field_name)) {
116 throw new NotFoundHttpException();
118 if (!$langcode || !$entity->hasTranslation($langcode)) {
119 throw new NotFoundHttpException();
122 $entity = $entity->getTranslation($langcode);
124 // If the entity information for this field is requested, include it.
125 $entity_id = $entity->getEntityTypeId() . '/' . $entity_id;
126 if (is_array($entities) && in_array($entity_id, $entities) && !isset($metadata[$entity_id])) {
127 $metadata[$entity_id] = $this->metadataGenerator->generateEntityMetadata($entity);
130 $metadata[$field] = $this->metadataGenerator->generateFieldMetadata($entity->get($field_name), $view_mode);
133 return new JsonResponse($metadata);
137 * Returns AJAX commands to load in-place editors' attachments.
139 * Given a list of in-place editor IDs as POST parameters, render AJAX
140 * commands to load those in-place editors.
142 * @return \Drupal\Core\Ajax\AjaxResponse
145 public function attachments(Request $request) {
146 $response = new AjaxResponse();
147 $editors = $request->request->get('editors');
148 if (!isset($editors)) {
149 throw new NotFoundHttpException();
152 $response->setAttachments($this->editorSelector->getEditorAttachments($editors));
158 * Returns a single field edit form as an Ajax response.
160 * @param \Drupal\Core\Entity\EntityInterface $entity
161 * The entity being edited.
162 * @param string $field_name
163 * The name of the field that is being edited.
164 * @param string $langcode
165 * The name of the language for which the field is being edited.
166 * @param string $view_mode_id
167 * The view mode the field should be rerendered in.
168 * @param \Symfony\Component\HttpFoundation\Request $request
169 * The current request object containing the search string.
171 * @return \Drupal\Core\Ajax\AjaxResponse
174 public function fieldForm(EntityInterface $entity, $field_name, $langcode, $view_mode_id, Request $request) {
175 $response = new AjaxResponse();
177 // Replace entity with PrivateTempStore copy if available and not resetting,
178 // init PrivateTempStore copy otherwise.
179 $tempstore_entity = $this->tempStoreFactory->get('quickedit')->get($entity->uuid());
180 if ($tempstore_entity && $request->request->get('reset') !== 'true') {
181 $entity = $tempstore_entity;
184 $this->tempStoreFactory->get('quickedit')->set($entity->uuid(), $entity);
187 $form_state = (new FormState())
188 ->set('langcode', $langcode)
190 ->addBuildInfo('args', [$entity, $field_name]);
191 $form = $this->formBuilder()->buildForm('Drupal\quickedit\Form\QuickEditFieldForm', $form_state);
193 if ($form_state->isExecuted()) {
194 // The form submission saved the entity in PrivateTempStore. Return the
195 // updated view of the field from the PrivateTempStore copy.
196 $entity = $this->tempStoreFactory->get('quickedit')->get($entity->uuid());
198 // Closure to render the field given a view mode.
199 $render_field_in_view_mode = function ($view_mode_id) use ($entity, $field_name, $langcode) {
200 return $this->renderField($entity, $field_name, $langcode, $view_mode_id);
203 // Re-render the updated field.
204 $output = $render_field_in_view_mode($view_mode_id);
206 // Re-render the updated field for other view modes (i.e. for other
207 // instances of the same logical field on the user's page).
208 $other_view_mode_ids = $request->request->get('other_view_modes') ?: [];
209 $other_view_modes = array_map($render_field_in_view_mode, array_combine($other_view_mode_ids, $other_view_mode_ids));
211 $response->addCommand(new FieldFormSavedCommand($output, $other_view_modes));
214 $output = $this->renderer->renderRoot($form);
215 // When working with a hidden form, we don't want its CSS/JS to be loaded.
216 if ($request->request->get('nocssjs') !== 'true') {
217 $response->setAttachments($form['#attached']);
219 $response->addCommand(new FieldFormCommand($output));
221 $errors = $form_state->getErrors();
222 if (count($errors)) {
224 '#type' => 'status_messages'
226 $response->addCommand(new FieldFormValidationErrorsCommand($this->renderer->renderRoot($status_messages)));
236 * If the view mode ID is not an Entity Display view mode ID, then the field
237 * was rendered using a custom render pipeline (not the Entity/Field API
240 * An example could be Views' render pipeline. In that case, the view mode ID
241 * would probably contain the View's ID, display and the row index.
243 * @param \Drupal\Core\Entity\EntityInterface $entity
244 * The entity being edited.
245 * @param string $field_name
246 * The name of the field that is being edited.
247 * @param string $langcode
248 * The name of the language for which the field is being edited.
249 * @param string $view_mode_id
250 * The view mode the field should be rerendered in. Either an Entity Display
251 * view mode ID, or a custom one. See hook_quickedit_render_field().
253 * @return \Drupal\Component\Render\MarkupInterface
256 * @see hook_quickedit_render_field()
258 protected function renderField(EntityInterface $entity, $field_name, $langcode, $view_mode_id) {
259 $entity_view_mode_ids = array_keys($this->entityManager()->getViewModes($entity->getEntityTypeId()));
260 if (in_array($view_mode_id, $entity_view_mode_ids)) {
261 $entity = \Drupal::entityManager()->getTranslationFromContext($entity, $langcode);
262 $output = $entity->get($field_name)->view($view_mode_id);
265 // Each part of a custom (non-Entity Display) view mode ID is separated
266 // by a dash; the first part must be the module name.
267 $mode_id_parts = explode('-', $view_mode_id, 2);
268 $module = reset($mode_id_parts);
269 $args = [$entity, $field_name, $view_mode_id, $langcode];
270 $output = $this->moduleHandler()->invoke($module, 'quickedit_render_field', $args);
273 return $this->renderer->renderRoot($output);
277 * Saves an entity into the database, from PrivateTempStore.
279 * @param \Drupal\Core\Entity\EntityInterface $entity
280 * The entity being edited.
282 * @return \Drupal\Core\Ajax\AjaxResponse
285 public function entitySave(EntityInterface $entity) {
286 // Take the entity from PrivateTempStore and save in entity storage.
287 // fieldForm() ensures that the PrivateTempStore copy exists ahead.
288 $tempstore = $this->tempStoreFactory->get('quickedit');
289 $tempstore->get($entity->uuid())->save();
290 $tempstore->delete($entity->uuid());
292 // Return information about the entity that allows a front end application
295 'entity_type' => $entity->getEntityTypeId(),
296 'entity_id' => $entity->id()
299 // Respond to client that the entity was saved properly.
300 $response = new AjaxResponse();
301 $response->addCommand(new EntitySavedCommand($output));