1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @file |
4
|
|
|
* Contains \Drupal\entity_browser\Controllers\EntityBrowserController. |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
namespace Drupal\entity_browser\Controllers; |
8
|
|
|
|
9
|
|
|
use Drupal\Core\Ajax\AjaxResponse; |
10
|
|
|
use Drupal\Core\Ajax\CloseModalDialogCommand; |
11
|
|
|
use Drupal\Core\Ajax\OpenModalDialogCommand; |
12
|
|
|
use Drupal\Core\Controller\ControllerBase; |
13
|
|
|
use Drupal\Core\Form\FormState; |
14
|
|
|
use Drupal\Core\Entity\EntityInterface; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Returns responses for entity browser routes. |
18
|
|
|
*/ |
19
|
|
|
class EntityBrowserController extends ControllerBase { |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Return an Ajax dialog command for editing a referenced entity. |
23
|
|
|
* |
24
|
|
|
* @param \Drupal\Core\Entity\EntityInterface $entity |
25
|
|
|
* An entity being edited. |
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) { |
32
|
|
|
// Load the right translation for referenced entity if it's exists |
33
|
|
|
// or create new translation if it does not exists. |
34
|
|
|
if ($entity->isTranslatable()) { |
35
|
|
|
$language = $this->languageManager()->getCurrentLanguage()->getId(); |
36
|
|
|
$entity = $entity->hasTranslation($language) ? $entity->getTranslation($language) : $entity->addTranslation($language, $entity->toArray()); |
37
|
|
|
} |
38
|
|
|
// Build the entity edit form. |
39
|
|
|
$form_object = $this->entityManager()->getFormObject($entity->getEntityTypeId(), 'edit'); |
40
|
|
|
$form_object->setEntity($entity); |
41
|
|
|
$form_state = (new FormState()) |
42
|
|
|
->setFormObject($form_object) |
43
|
|
|
->disableRedirect(); |
44
|
|
|
// Building the form also submits. |
45
|
|
|
$form = $this->formBuilder()->buildForm($form_object, $form_state); |
46
|
|
|
|
47
|
|
|
// Return a response, depending on whether it's successfully submitted. |
48
|
|
|
if (!$form_state->isExecuted()) { |
49
|
|
|
// Return the form as a modal dialog. |
50
|
|
|
$form['#attached']['library'][] = 'core/drupal.dialog.ajax'; |
51
|
|
|
$title = $this->t('Edit entity @entity', ['@entity' => $entity->label()]); |
52
|
|
|
$response = AjaxResponse::create()->addCommand(new OpenModalDialogCommand($title, $form, ['width' => 800])); |
53
|
|
|
return $response; |
54
|
|
|
} |
55
|
|
|
else { |
56
|
|
|
// Return command for closing the modal. |
57
|
|
|
return AjaxResponse::create()->addCommand(new CloseModalDialogCommand()); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
} |
62
|
|
|
|