3 namespace Drupal\entity_browser\Controllers;
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;
15 * Returns responses for entity browser routes.
17 class EntityBrowserController extends ControllerBase {
20 * Return an Ajax dialog command for editing a referenced entity.
22 * @param \Drupal\Core\Entity\EntityInterface $entity
23 * An entity being edited.
24 * @param \Symfony\Component\HttpFoundation\Request $request
25 * The currently processing request.
27 * @return \Drupal\Core\Ajax\AjaxResponse
28 * An Ajax response with a command for opening or closing the dialog
29 * containing the edit form.
31 public function entityBrowserEdit(EntityInterface $entity, Request $request) {
33 // Use edit form class if it exists, otherwise use default form class.
34 $operation = 'default';
35 $entity_type = $entity->getEntityType();
36 if ($entity_type->getFormClass('edit')) {
40 // Build the entity edit form.
41 $form_object = $this->entityTypeManager()->getFormObject($entity->getEntityTypeId(), $operation);
42 $form_object->setEntity($entity);
43 $form_state = (new FormState())
44 ->setFormObject($form_object)
46 // Building the form also submits.
47 $form = $this->formBuilder()->buildForm($form_object, $form_state);
49 // Return a response, depending on whether it's successfully submitted.
50 if (!$form_state->isExecuted()) {
51 // Return the form as a modal dialog.
52 $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
53 $title = $this->t('Edit entity @entity', ['@entity' => $entity->label()]);
54 $response = AjaxResponse::create()->addCommand(new OpenDialogCommand('#' . $entity->getEntityTypeId() . '-' . $entity->id() . '-edit-dialog', $title, $form, ['modal' => TRUE, 'width' => 800]));
58 // Return command for closing the modal.
59 $response = AjaxResponse::create()->addCommand(new CloseDialogCommand('#' . $entity->getEntityTypeId() . '-' . $entity->id() . '-edit-dialog'));
60 // Also refresh the widget if "details_id" is provided.
61 $details_id = $request->query->get('details_id');
62 if (!empty($details_id)) {
63 $response->addCommand(new ValueUpdatedCommand($details_id));