View source
<?php
namespace Drupal\entity_embed\Form;
use Drupal\Component\Utility\Html;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\SetDialogTitleCommand;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Entity\TranslatableInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\editor\Ajax\EditorDialogSave;
use Drupal\editor\EditorInterface;
use Drupal\embed\EmbedButtonInterface;
use Drupal\entity_browser\Events\Events;
use Drupal\entity_browser\Events\RegisterJSCallbacks;
use Drupal\entity_embed\EntityEmbedDisplay\EntityEmbedDisplayManager;
use Drupal\Component\Serialization\Json;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class EntityEmbedDialog extends FormBase {
protected $entityEmbedDisplayManager;
protected $formBuilder;
protected $entityTypeManager;
protected $eventDispatcher;
protected $entityBrowser;
protected $entityFieldManager;
protected $moduleHandler;
protected $entityBrowserSettings = [];
public function __construct(EntityEmbedDisplayManager $entity_embed_display_manager, FormBuilderInterface $form_builder, EntityTypeManagerInterface $entity_type_manager, EventDispatcherInterface $event_dispatcher, EntityFieldManagerInterface $entity_field_manager, ModuleHandlerInterface $module_handler) {
$this->entityEmbedDisplayManager = $entity_embed_display_manager;
$this->formBuilder = $form_builder;
$this->entityTypeManager = $entity_type_manager;
$this->eventDispatcher = $event_dispatcher;
$this->entityFieldManager = $entity_field_manager;
$this->moduleHandler = $module_handler;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.manager.entity_embed.display'), $container
->get('form_builder'), $container
->get('entity_type.manager'), $container
->get('event_dispatcher'), $container
->get('entity_field.manager'), $container
->get('module_handler'), $container
->get('language_manager'));
}
public function getFormId() {
return 'entity_embed_dialog';
}
protected function loadEntityByAttributes(array $attributes) {
$entity = $this->entityTypeManager
->getStorage($attributes['data-entity-type'])
->loadByProperties([
'uuid' => $attributes['data-entity-uuid'],
]);
$entity = current($entity);
if ($entity && $entity instanceof TranslatableInterface && !empty($attributes['data-langcode'])) {
if ($entity
->hasTranslation($attributes['data-langcode'])) {
$entity = $entity
->getTranslation($attributes['data-langcode']);
}
}
return $entity;
}
public function buildForm(array $form, FormStateInterface $form_state, EditorInterface $editor = NULL, EmbedButtonInterface $embed_button = NULL) {
$values = $form_state
->getValues();
$input = $form_state
->getUserInput();
$form_state
->set('embed_button', $embed_button);
$form_state
->set('editor', $editor);
$entity_element = empty($values['attributes']) ? [] : $values['attributes'];
$entity_element += empty($input['attributes']) ? [] : $input['attributes'];
if (!$form_state
->get('entity_element')) {
$form_state
->set('entity_element', isset($input['editor_object']) ? $input['editor_object'] : []);
}
$entity_element += $form_state
->get('entity_element');
$entity_element += [
'data-entity-type' => $embed_button
->getTypeSetting('entity_type'),
'data-entity-uuid' => '',
'data-entity-embed-display' => 'entity_reference:entity_reference_entity_view',
'data-entity-embed-display-settings' => isset($form_state
->get('entity_element')['data-entity-embed-settings']) ? $form_state
->get('entity_element')['data-entity-embed-settings'] : [],
];
$form_state
->set('entity_element', $entity_element);
$entity = $this
->loadEntityByAttributes($entity_element);
$form_state
->set('entity', $entity ?: NULL);
if (!$form_state
->get('step')) {
if ($form_state
->get('entity')) {
$form_state
->set('step', 'embed');
}
else {
$form_state
->set('step', 'select');
}
}
$form['#tree'] = TRUE;
$form['#attached']['library'][] = 'editor/drupal.editor.dialog';
$form['#attached']['library'][] = 'entity_embed/drupal.entity_embed.dialog';
$form['#prefix'] = '<div id="entity-embed-dialog-form">';
$form['#suffix'] = '</div>';
$form['#attributes']['class'][] = 'entity-embed-dialog-step--' . $form_state
->get('step');
$this
->loadEntityBrowser($form_state);
if ($form_state
->get('step') == 'select') {
$form = $this
->buildSelectStep($form, $form_state);
}
elseif ($form_state
->get('step') == 'review') {
$form = $this
->buildReviewStep($form, $form_state);
}
elseif ($form_state
->get('step') == 'embed') {
$form = $this
->buildEmbedStep($form, $form_state);
}
return $form;
}
public function buildSelectStep(array $form, FormStateInterface $form_state) {
$entity_element = $form_state
->get('entity_element');
$embed_button = $form_state
->get('embed_button');
$entity = $form_state
->get('entity');
$form['attributes']['data-entity-type'] = [
'#type' => 'value',
'#value' => $entity_element['data-entity-type'],
];
$label = $this
->t('Label');
$entity_type = $this->entityTypeManager
->getDefinition($entity_element['data-entity-type']);
if ($entity_type
->entityClassImplements(FieldableEntityInterface::class) && $entity_type
->hasKey('label')) {
$field_definitions = $this->entityFieldManager
->getBaseFieldDefinitions($entity_type
->id());
if (isset($field_definitions[$entity_type
->getKey('label')])) {
$label = $field_definitions[$entity_type
->getKey('label')]
->getLabel();
}
}
$form['#title'] = $this
->t('Select @type to embed', [
'@type' => $entity_type
->getSingularLabel(),
]);
if ($this->entityBrowser) {
$this->eventDispatcher
->addListener(Events::REGISTER_JS_CALLBACKS, [
$this,
'registerJSCallback',
]);
$form['entity_browser'] = [
'#type' => 'entity_browser',
'#entity_browser' => $this->entityBrowser
->id(),
'#cardinality' => 1,
'#entity_browser_validators' => [
'entity_type' => [
'type' => $entity_element['data-entity-type'],
],
],
];
}
else {
$form['entity_id'] = [
'#type' => 'entity_autocomplete',
'#target_type' => $entity_element['data-entity-type'],
'#title' => $label,
'#default_value' => $entity,
'#required' => TRUE,
'#description' => $this
->t('Type label and pick the right one from suggestions. Note that the unique ID will be saved.'),
'#maxlength' => 255,
];
if ($bundles = $embed_button
->getTypeSetting('bundles')) {
$form['entity_id']['#selection_settings']['target_bundles'] = $bundles;
}
}
if (!empty($entity_element['data-langcode'])) {
$form['attributes']['data-langcode'] = [
'#type' => 'hidden',
'#value' => $entity_element['data-langcode'],
];
}
$form['attributes']['data-entity-uuid'] = [
'#type' => 'value',
'#title' => $entity_element['data-entity-uuid'],
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['save_modal'] = [
'#type' => 'submit',
'#value' => $this
->t('Next'),
'#button_type' => 'primary',
'#submit' => [],
'#ajax' => [
'callback' => '::submitSelectStep',
'event' => 'click',
],
'#attributes' => [
'class' => [
'js-button-next',
],
],
];
return $form;
}
public function buildReviewStep(array $form, FormStateInterface $form_state) {
$entity = $form_state
->get('entity');
$form['#title'] = $this
->t('Review selected @type', [
'@type' => $entity
->getEntityType()
->getSingularLabel(),
]);
$form['selection'] = [
'#markup' => $entity
->label(),
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['back'] = [
'#type' => 'submit',
'#value' => $this
->t('Replace selection'),
'#submit' => [],
'#ajax' => [
'callback' => '::submitAndShowSelect',
'event' => 'click',
],
];
$form['actions']['save_modal'] = [
'#type' => 'submit',
'#value' => $this
->t('Next'),
'#button_type' => 'primary',
'#submit' => [],
'#ajax' => [
'callback' => '::submitAndShowEmbed',
'event' => 'click',
],
'#attributes' => [
'class' => [
'js-button-next',
],
],
];
return $form;
}
public function buildEmbedStep(array $form, FormStateInterface $form_state) {
$entity_element = $form_state
->get('entity_element');
$embed_button = $form_state
->get('embed_button');
$editor = $form_state
->get('editor');
$entity = $form_state
->get('entity');
$values = $form_state
->getValues();
$form['#title'] = $this
->t('Embed @type', [
'@type' => $entity
->getEntityType()
->getSingularLabel(),
]);
try {
if ($entity
->getEntityType()
->hasLinkTemplate('canonical')) {
$options = [
'attributes' => [
'target' => '_blank',
],
];
$entity_label = $entity
->toLink($entity
->label(), 'canonical', $options)
->toString();
}
elseif ($entity
->getEntityTypeId() == 'file') {
$entity_label = '<a href="' . file_create_url($entity
->getFileUri()) . '" target="_blank">' . $entity
->label() . '</a>';
}
else {
$entity_label = '<a href="' . $entity
->toUrl()
->toString() . '" target="_blank">' . $entity
->label() . '</a>';
}
} catch (\Exception $e) {
$entity_label = $entity
->label();
}
$form['entity'] = [
'#type' => 'item',
'#title' => $this
->t('Selected entity'),
'#markup' => $entity_label,
];
$form['attributes']['data-entity-type'] = [
'#type' => 'hidden',
'#value' => $entity_element['data-entity-type'],
];
$form['attributes']['data-entity-uuid'] = [
'#type' => 'hidden',
'#value' => $entity_element['data-entity-uuid'],
];
if (!empty($entity_element['data-langcode'])) {
$form['attributes']['data-langcode'] = [
'#type' => 'hidden',
'#value' => $entity_element['data-langcode'],
];
}
$display_plugin_options = $this
->getDisplayPluginOptions($embed_button, $entity);
if (!isset($display_plugin_options[$entity_element['data-entity-embed-display']])) {
$entity_element['data-entity-embed-display'] = key($display_plugin_options);
}
if ($entity_element['data-entity-embed-display'] === 'default') {
$entity_element['data-entity-embed-display'] = 'entity_reference:entity_reference_entity_view';
}
$form['attributes']['data-entity-embed-display'] = [
'#type' => 'select',
'#title' => $this
->t('Display as'),
'#options' => $display_plugin_options,
'#default_value' => $entity_element['data-entity-embed-display'],
'#required' => TRUE,
'#ajax' => [
'callback' => '::updatePluginConfigurationForm',
'wrapper' => 'data-entity-embed-display-settings-wrapper',
'effect' => 'fade',
],
'#access' => count($display_plugin_options) > 1,
];
$form['attributes']['data-entity-embed-display-settings'] = [
'#type' => 'container',
'#prefix' => '<div id="data-entity-embed-display-settings-wrapper">',
'#suffix' => '</div>',
];
$form['attributes']['data-embed-button'] = [
'#type' => 'value',
'#value' => $embed_button
->id(),
];
$plugin_id = !empty($values['attributes']['data-entity-embed-display']) ? $values['attributes']['data-entity-embed-display'] : $entity_element['data-entity-embed-display'];
if (!empty($plugin_id)) {
if (empty($entity_element['data-entity-embed-display-settings'])) {
$entity_element['data-entity-embed-display-settings'] = [];
}
elseif (is_string($entity_element['data-entity-embed-display-settings'])) {
$entity_element['data-entity-embed-display-settings'] = Json::decode($entity_element['data-entity-embed-display-settings']);
}
$display = $this->entityEmbedDisplayManager
->createInstance($plugin_id, $entity_element['data-entity-embed-display-settings']);
$display
->setContextValue('entity', $entity);
$display
->setAttributes($entity_element);
$form['attributes']['data-entity-embed-display-settings'] += $display
->buildConfigurationForm($form, $form_state);
}
if ($editor
->getFilterFormat()
->filters('filter_align')->status) {
$form['attributes']['data-align'] = [
'#title' => $this
->t('Align'),
'#type' => 'radios',
'#options' => [
'' => $this
->t('None'),
'left' => $this
->t('Left'),
'center' => $this
->t('Center'),
'right' => $this
->t('Right'),
],
'#default_value' => isset($entity_element['data-align']) ? $entity_element['data-align'] : '',
'#wrapper_attributes' => [
'class' => [
'container-inline',
],
],
'#attributes' => [
'class' => [
'container-inline',
],
],
];
}
if ($editor
->getFilterFormat()
->filters('filter_caption')->status) {
$form['attributes']['data-caption'] = [
'#title' => $this
->t('Caption'),
'#type' => 'textarea',
'#rows' => 3,
'#default_value' => isset($entity_element['data-caption']) ? Html::decodeEntities($entity_element['data-caption']) : '',
'#element_validate' => [
'::escapeValue',
],
];
}
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['back'] = [
'#type' => 'submit',
'#value' => $this
->t('Back'),
'#submit' => [],
'#ajax' => [
'callback' => !empty($this->entityBrowserSettings['display_review']) ? '::submitAndShowReview' : '::submitAndShowSelect',
'event' => 'click',
],
];
$form['actions']['save_modal'] = [
'#type' => 'submit',
'#value' => $this
->t('Embed'),
'#button_type' => 'primary',
'#submit' => [],
'#ajax' => [
'callback' => '::submitEmbedStep',
'event' => 'click',
],
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
if ($form_state
->get('step') == 'select') {
$this
->validateSelectStep($form, $form_state);
}
elseif ($form_state
->get('step') == 'embed') {
$this
->validateEmbedStep($form, $form_state);
}
}
public function validateSelectStep(array $form, FormStateInterface $form_state) {
if ($form_state
->hasValue([
'entity_browser',
'entities',
])) {
if (count($form_state
->getValue([
'entity_browser',
'entities',
])) > 0) {
$id = $form_state
->getValue([
'entity_browser',
'entities',
0,
])
->id();
}
$element = $form['entity_browser'];
}
else {
$id = trim($form_state
->getValue([
'entity_id',
]));
$element = $form['entity_id'];
}
$entity_type = $form_state
->getValue([
'attributes',
'data-entity-type',
]);
if (!isset($id)) {
$form_state
->setError($element, $this
->t('No entity selected.'));
return;
}
if ($entity = $this->entityTypeManager
->getStorage($entity_type)
->load($id)) {
if (!$entity
->access('view')) {
$form_state
->setError($element, $this
->t('Unable to access @type entity @id.', [
'@type' => $entity_type,
'@id' => $id,
]));
}
else {
if ($uuid = $entity
->uuid()) {
$form_state
->setValueForElement($form['attributes']['data-entity-uuid'], $uuid);
}
else {
$form_state
->setError($element, $this
->t('Cannot embed @type entity @id because it does not have a UUID.', [
'@type' => $entity_type,
'@id' => $id,
]));
}
$embed_button = $form_state
->get('embed_button');
$display_plugin_options = $this
->getDisplayPluginOptions($embed_button, $entity);
if (empty($display_plugin_options)) {
$form_state
->setError($element, $this
->t('No display options available for the selected %entity-type. Please select another %entity_type.', [
'%entity_type' => $entity
->getEntityType()
->getLabel(),
]));
$this
->logger('entity_embed')
->warning('No display options available for "@type:" entity "@id" while embedding using button "@button". Please ensure that at least one Entity Embed Display plugin is allowed for this embed button which is available for this entity.', [
'@type' => $entity_type,
'@id' => $entity
->id(),
'@button' => $embed_button
->id(),
]);
}
}
}
else {
$form_state
->setError($element, $this
->t('Unable to load @type entity @id.', [
'@type' => $entity_type,
'@id' => $id,
]));
}
}
public function validateEmbedStep(array $form, FormStateInterface $form_state) {
$entity_element = $form_state
->getValue('attributes');
$entity = $form_state
->get('entity');
$plugin_id = $entity_element['data-entity-embed-display'];
$plugin_settings = !empty($entity_element['data-entity-embed-display-settings']) ? $entity_element['data-entity-embed-display-settings'] : [];
$display = $this->entityEmbedDisplayManager
->createInstance($plugin_id, $plugin_settings);
$display
->setContextValue('entity', $entity);
$display
->setAttributes($entity_element);
$display
->validateConfigurationForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
}
public function updatePluginConfigurationForm(array &$form, FormStateInterface $form_state) {
return $form['attributes']['data-entity-embed-display-settings'];
}
public function submitStep(array &$form, FormStateInterface $form_state, $step) {
$response = new AjaxResponse();
$form_state
->set('step', $step);
$form_state
->setRebuild(TRUE);
$rebuild_form = $this->formBuilder
->rebuildForm('entity_embed_dialog', $form_state, $form);
unset($rebuild_form['#prefix'], $rebuild_form['#suffix']);
$response
->addCommand(new HtmlCommand('#entity-embed-dialog-form', $rebuild_form));
$response
->addCommand(new SetDialogTitleCommand('', $rebuild_form['#title']));
return $response;
}
public function submitSelectStep(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
if ($form_state
->hasAnyErrors()) {
unset($form['#prefix'], $form['#suffix']);
$form['status_messages'] = [
'#type' => 'status_messages',
'#weight' => -10,
];
$response
->addCommand(new HtmlCommand('#entity-embed-dialog-form', $form));
}
else {
$form_state
->set('step', !empty($this->entityBrowserSettings['display_review']) ? 'review' : 'embed');
$form_state
->setRebuild(TRUE);
$rebuild_form = $this->formBuilder
->rebuildForm('entity_embed_dialog', $form_state, $form);
unset($rebuild_form['#prefix'], $rebuild_form['#suffix']);
$response
->addCommand(new HtmlCommand('#entity-embed-dialog-form', $rebuild_form));
$response
->addCommand(new SetDialogTitleCommand('', $rebuild_form['#title']));
}
return $response;
}
public function submitAndShowSelect(array &$form, FormStateInterface $form_state) {
return $this
->submitStep($form, $form_state, 'select');
}
public function submitAndShowReview(array &$form, FormStateInterface $form_state) {
return $this
->submitStep($form, $form_state, 'review');
}
public function submitAndShowEmbed(array $form, FormStateInterface $form_state) {
return $this
->submitStep($form, $form_state, 'embed');
}
public function submitEmbedStep(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$entity_element = $form_state
->getValue('attributes');
$entity = $this
->loadEntityByAttributes($entity_element);
$plugin_id = $entity_element['data-entity-embed-display'];
$plugin_settings = !empty($entity_element['data-entity-embed-display-settings']) ? $entity_element['data-entity-embed-display-settings'] : [];
$display = $this->entityEmbedDisplayManager
->createInstance($plugin_id, $plugin_settings);
$display
->setContextValue('entity', $entity);
$display
->setAttributes($entity_element);
$display
->submitConfigurationForm($form, $form_state);
$values = $form_state
->getValues();
if ($form_state
->hasAnyErrors()) {
unset($form['#prefix'], $form['#suffix']);
$form['status_messages'] = [
'#type' => 'status_messages',
'#weight' => -10,
];
$response
->addCommand(new HtmlCommand('#entity-embed-dialog-form', $form));
}
else {
if (!empty($values['attributes']['data-entity-embed-display-settings'])) {
$values['attributes']['data-entity-embed-display-settings'] = Json::encode($values['attributes']['data-entity-embed-display-settings']);
}
$values['attributes'] = array_filter($values['attributes'], function ($value) {
return (bool) mb_strlen((string) $value);
});
$this->moduleHandler
->alter('entity_embed_values', $values, $entity, $display);
$response
->addCommand(new EditorDialogSave($values));
$response
->addCommand(new CloseModalDialogCommand());
}
return $response;
}
public static function escapeValue($element, FormStateInterface $form_state) {
if ($value = trim($element['#value'])) {
$form_state
->setValueForElement($element, Html::escape($value));
}
}
public function getDisplayPluginOptions(EmbedButtonInterface $embed_button, EntityInterface $entity) {
$plugins = $this->entityEmbedDisplayManager
->getDefinitionOptionsForContext([
'entity' => $entity,
'entity_type' => $entity
->getEntityTypeId(),
'embed_button' => $embed_button,
]);
return $plugins;
}
public function registerJSCallback(RegisterJSCallbacks $event) {
if ($event
->getBrowserID() == $this->entityBrowser
->id()) {
$event
->registerCallback('Drupal.entityEmbedDialog.selectionCompleted');
}
}
protected function loadEntityBrowser(FormStateInterface $form_state) {
$this->entityBrowser = NULL;
$this->entityBrowserSettings = [];
$embed_button = $form_state
->get('embed_button');
if ($embed_button && ($entity_browser_id = $embed_button
->getTypePlugin()
->getConfigurationValue('entity_browser'))) {
$this->entityBrowser = $this->entityTypeManager
->getStorage('entity_browser')
->load($entity_browser_id);
$this->entityBrowserSettings = $embed_button
->getTypePlugin()
->getConfigurationValue('entity_browser_settings');
}
}
}