Version 1
[yaffs-website] / web / modules / contrib / entity_browser / src / Controllers / EntityBrowserController.php
1 <?php
2
3 namespace Drupal\entity_browser\Controllers;
4
5 use Drupal\Core\Ajax\AjaxResponse;
6 use Drupal\Core\Ajax\CloseDialogCommand;
7 use Drupal\Core\Ajax\OpenDialogCommand;
8 use Drupal\Core\Controller\ControllerBase;
9 use Drupal\Core\Form\FormState;
10 use Drupal\Core\Entity\EntityInterface;
11 use Drupal\entity_browser\Ajax\ValueUpdatedCommand;
12 use Symfony\Component\HttpFoundation\Request;
13
14 /**
15  * Returns responses for entity browser routes.
16  */
17 class EntityBrowserController extends ControllerBase {
18
19   /**
20    * Return an Ajax dialog command for editing a referenced entity.
21    *
22    * @param \Drupal\Core\Entity\EntityInterface $entity
23    *   An entity being edited.
24    * @param \Symfony\Component\HttpFoundation\Request $request
25    *   The currently processing request.
26    *
27    * @return \Drupal\Core\Ajax\AjaxResponse
28    *   An Ajax response with a command for opening or closing the dialog
29    *   containing the edit form.
30    */
31   public function entityBrowserEdit(EntityInterface $entity, Request $request) {
32     // Build the entity edit form.
33     $form_object = $this->entityTypeManager()->getFormObject($entity->getEntityTypeId(), 'edit');
34     $form_object->setEntity($entity);
35     $form_state = (new FormState())
36       ->setFormObject($form_object)
37       ->disableRedirect();
38     // Building the form also submits.
39     $form = $this->formBuilder()->buildForm($form_object, $form_state);
40
41     // Return a response, depending on whether it's successfully submitted.
42     if (!$form_state->isExecuted()) {
43       // Return the form as a modal dialog.
44       $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
45       $title = $this->t('Edit entity @entity', ['@entity' => $entity->label()]);
46       $response = AjaxResponse::create()->addCommand(new OpenDialogCommand('#' . $entity->getEntityTypeId() . '-' . $entity->id() . '-edit-dialog', $title, $form, ['modal' => TRUE, 'width' => 800]));
47       return $response;
48     }
49     else {
50       // Return command for closing the modal.
51       $response = AjaxResponse::create()->addCommand(new CloseDialogCommand('#' . $entity->getEntityTypeId() . '-' . $entity->id() . '-edit-dialog'));
52       // Also refresh the widget if "details_id" is provided.
53       $details_id = $request->query->get('details_id');
54       if (!empty($details_id)) {
55         $response->addCommand(new ValueUpdatedCommand($details_id));
56       }
57       return $response;
58     }
59   }
60
61 }