first commit

This commit is contained in:
2020-06-08 23:57:36 +02:00
commit 6277454f7a
16057 changed files with 1715382 additions and 0 deletions
@@ -0,0 +1,10 @@
<?php
namespace Drupal\quickedit\Access;
/**
* @deprecated in drupal:8.4.0 and is removed from drupal:9.0.0.
*/
class EditEntityFieldAccessCheck extends QuickEditEntityFieldAccessCheck {
}
@@ -0,0 +1,10 @@
<?php
namespace Drupal\quickedit\Access;
/**
* @deprecated in drupal:8.4.0 and is removed from drupal:9.0.0.
*/
interface EditEntityFieldAccessCheckInterface extends QuickEditEntityFieldAccessCheckInterface {
}
@@ -0,0 +1,62 @@
<?php
namespace Drupal\quickedit\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\EntityInterface;
/**
* Access check for in-place editing entity fields.
*/
class QuickEditEntityFieldAccessCheck implements AccessInterface, QuickEditEntityFieldAccessCheckInterface {
/**
* Checks Quick Edit access to the field.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity containing the field.
* @param string $field_name
* The field name.
* @param string $langcode
* The langcode.
* @param \Drupal\Core\Session\AccountInterface $account
* The currently logged in account.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*
* @todo Use the $account argument: https://www.drupal.org/node/2266809.
*/
public function access(EntityInterface $entity, $field_name, $langcode, AccountInterface $account) {
if (!$this->validateRequestAttributes($entity, $field_name, $langcode)) {
return AccessResult::forbidden();
}
return $this->accessEditEntityField($entity, $field_name);
}
/**
* {@inheritdoc}
*/
public function accessEditEntityField(EntityInterface $entity, $field_name) {
return $entity->access('update', NULL, TRUE)->andIf($entity->get($field_name)->access('edit', NULL, TRUE));
}
/**
* Validates request attributes.
*/
protected function validateRequestAttributes(EntityInterface $entity, $field_name, $langcode) {
// Validate the field name and language.
if (!$field_name || !$entity->hasField($field_name)) {
return FALSE;
}
if (!$langcode || !$entity->hasTranslation($langcode)) {
return FALSE;
}
return TRUE;
}
}
@@ -0,0 +1,25 @@
<?php
namespace Drupal\quickedit\Access;
use Drupal\Core\Entity\EntityInterface;
/**
* Access check for in-place editing entity fields.
*/
interface QuickEditEntityFieldAccessCheckInterface {
/**
* Checks access to edit the requested field of the requested entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
* @param string $field_name
* The field name.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function accessEditEntityField(EntityInterface $entity, $field_name);
}
@@ -0,0 +1,23 @@
<?php
namespace Drupal\quickedit\Ajax;
use Drupal\Core\Ajax\BaseCommand;
/**
* AJAX command to indicate the entity was loaded from PrivateTempStore and
* saved into the database.
*/
class EntitySavedCommand extends BaseCommand {
/**
* Constructs a EntitySaveCommand object.
*
* @param string $data
* The data to pass on to the client side.
*/
public function __construct($data) {
parent::__construct('quickeditEntitySaved', $data);
}
}
@@ -0,0 +1,23 @@
<?php
namespace Drupal\quickedit\Ajax;
use Drupal\Core\Ajax\BaseCommand;
/**
* AJAX command for passing a rendered field form to Quick Edit's JavaScript
* app.
*/
class FieldFormCommand extends BaseCommand {
/**
* Constructs a FieldFormCommand object.
*
* @param string $data
* The data to pass on to the client side.
*/
public function __construct($data) {
parent::__construct('quickeditFieldForm', $data);
}
}
@@ -0,0 +1,47 @@
<?php
namespace Drupal\quickedit\Ajax;
use Drupal\Core\Ajax\BaseCommand;
/**
* AJAX command to indicate a field was saved into PrivateTempStore without
* validation errors and pass the rerendered field to Quick Edit's JavaScript
* app.
*/
class FieldFormSavedCommand extends BaseCommand {
/**
* The same re-rendered edited field, but in different view modes.
*
* @var array
*/
protected $other_view_modes;
/**
* Constructs a FieldFormSavedCommand object.
*
* @param string $data
* The re-rendered edited field to pass on to the client side.
* @param array $other_view_modes
* The same re-rendered edited field, but in different view modes, for other
* instances of the same field on the user's page. Keyed by view mode.
*/
public function __construct($data, $other_view_modes = []) {
parent::__construct('quickeditFieldFormSaved', $data);
$this->other_view_modes = $other_view_modes;
}
/**
* {@inheritdoc}
*/
public function render() {
return [
'command' => $this->command,
'data' => $this->data,
'other_view_modes' => $this->other_view_modes,
];
}
}
@@ -0,0 +1,23 @@
<?php
namespace Drupal\quickedit\Ajax;
use Drupal\Core\Ajax\BaseCommand;
/**
* AJAX command to indicate a field form was attempted to be saved but failed
* validation and pass the validation errors.
*/
class FieldFormValidationErrorsCommand extends BaseCommand {
/**
* Constructs a FieldFormValidationErrorsCommand object.
*
* @param string $data
* The data to pass on to the client side.
*/
public function __construct($data) {
parent::__construct('quickeditFieldFormValidationErrors', $data);
}
}
@@ -0,0 +1,37 @@
<?php
namespace Drupal\quickedit\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* Defines an InPlaceEditor annotation object.
*
* Plugin Namespace: Plugin\InPlaceEditor
*
* For a working example, see \Drupal\quickedit\Plugin\InPlaceEditor\PlainTextEditor
*
* @see \Drupal\quickedit\Plugin\InPlaceEditorBase
* @see \Drupal\quickedit\Plugin\InPlaceEditorInterface
* @see \Drupal\quickedit\Plugin\InPlaceEditorManager
* @see plugin_api
*
* @Annotation
*/
class InPlaceEditor extends Plugin {
/**
* The plugin ID.
*
* @var string
*/
public $id;
/**
* The name of the module providing the in-place editor plugin.
*
* @var string
*/
public $module;
}
@@ -0,0 +1,101 @@
<?php
namespace Drupal\quickedit;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterPluginManager;
/**
* Selects an in-place editor (an InPlaceEditor plugin) for a field.
*/
class EditorSelector implements EditorSelectorInterface {
/**
* The manager for editor plugins.
*
* @var \Drupal\Component\Plugin\PluginManagerInterface
*/
protected $editorManager;
/**
* The manager for formatter plugins.
*
* @var \Drupal\Core\Field\FormatterPluginManager
*/
protected $formatterManager;
/**
* A list of alternative editor plugin IDs, keyed by editor plugin ID.
*
* @var array
*/
protected $alternatives;
/**
* Constructs a new EditorSelector.
*
* @param \Drupal\Component\Plugin\PluginManagerInterface $editor_manager
* The manager for editor plugins.
* @param \Drupal\Core\Field\FormatterPluginManager $formatter_manager
* The manager for formatter plugins.
*/
public function __construct(PluginManagerInterface $editor_manager, FormatterPluginManager $formatter_manager) {
$this->editorManager = $editor_manager;
$this->formatterManager = $formatter_manager;
}
/**
* {@inheritdoc}
*/
public function getEditor($formatter_type, FieldItemListInterface $items) {
// Check if the formatter defines an appropriate in-place editor. For
// example, text formatters displaying plain text can choose to use the
// 'plain_text' editor. If the formatter doesn't specify, fall back to the
// 'form' editor, since that can work for any field. Formatter definitions
// can use 'disabled' to explicitly opt out of in-place editing.
$formatter_info = $this->formatterManager->getDefinition($formatter_type);
$editor_id = $formatter_info['quickedit']['editor'];
if ($editor_id === 'disabled') {
return;
}
elseif ($editor_id === 'form') {
return 'form';
}
// No early return, so create a list of all choices.
$editor_choices = [$editor_id];
if (isset($this->alternatives[$editor_id])) {
$editor_choices = array_merge($editor_choices, $this->alternatives[$editor_id]);
}
// Make a choice.
foreach ($editor_choices as $editor_id) {
$editor = $this->editorManager->createInstance($editor_id);
if ($editor->isCompatible($items)) {
return $editor_id;
}
}
// We still don't have a choice, so fall back to the default 'form' editor.
return 'form';
}
/**
* {@inheritdoc}
*/
public function getEditorAttachments(array $editor_ids) {
$attachments = [];
$editor_ids = array_unique($editor_ids);
// Editor plugins' attachments.
foreach ($editor_ids as $editor_id) {
$editor = $this->editorManager->createInstance($editor_id);
$attachments[] = $editor->getAttachments();
}
return NestedArray::mergeDeepArray($attachments);
}
}
@@ -0,0 +1,38 @@
<?php
namespace Drupal\quickedit;
use Drupal\Core\Field\FieldItemListInterface;
/**
* Interface for selecting an in-place editor (an Editor plugin) for a field.
*/
interface EditorSelectorInterface {
/**
* Returns the in-place editor (an InPlaceEditor plugin) to use for a field.
*
* @param string $formatter_type
* The field's formatter type name.
* @param \Drupal\Core\Field\FieldItemListInterface $items
* The field values to be in-place edited.
*
* @return string|null
* The editor to use, or NULL to not enable in-place editing.
*/
public function getEditor($formatter_type, FieldItemListInterface $items);
/**
* Returns the attachments for all editors.
*
* @param array $editor_ids
* A list of all in-place editor IDs that should be attached.
*
* @return array
* An array of attachments, for use with #attached.
*
* @see \Drupal\Core\Render\AttachmentsResponseProcessorInterface::processAttachments()
*/
public function getEditorAttachments(array $editor_ids);
}
@@ -0,0 +1,227 @@
<?php
namespace Drupal\quickedit\Form;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Builds and process a form for editing a single entity field.
*
* @internal
*/
class QuickEditFieldForm extends FormBase {
/**
* Stores the tempstore factory.
*
* @var \Drupal\Core\TempStore\PrivateTempStoreFactory
*/
protected $tempStoreFactory;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The node type storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeTypeStorage;
/**
* Constructs a new EditFieldForm.
*
* @param \Drupal\Core\TempStore\PrivateTempStoreFactory $temp_store_factory
* The tempstore factory.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Entity\EntityStorageInterface $node_type_storage
* The node type storage.
*/
public function __construct(PrivateTempStoreFactory $temp_store_factory, ModuleHandlerInterface $module_handler, EntityStorageInterface $node_type_storage) {
$this->moduleHandler = $module_handler;
$this->nodeTypeStorage = $node_type_storage;
$this->tempStoreFactory = $temp_store_factory;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('tempstore.private'),
$container->get('module_handler'),
$container->get('entity_type.manager')->getStorage('node_type')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'quickedit_field_form';
}
/**
* {@inheritdoc}
*
* Builds a form for a single entity field.
*/
public function buildForm(array $form, FormStateInterface $form_state, EntityInterface $entity = NULL, $field_name = NULL) {
if (!$form_state->has('entity')) {
$this->init($form_state, $entity, $field_name);
}
// Add the field form.
$form_state->get('form_display')->buildForm($entity, $form, $form_state);
// Add a dummy changed timestamp field to attach form errors to.
if ($entity instanceof EntityChangedInterface) {
$form['changed_field'] = [
'#type' => 'hidden',
'#value' => $entity->getChangedTime(),
];
}
// Add a submit button. Give it a class for easy JavaScript targeting.
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => t('Save'),
'#attributes' => ['class' => ['quickedit-form-submit']],
];
// Use the non-inline form error display for Quick Edit forms, because in
// this case the errors are already near the form element.
$form['#disable_inline_form_errors'] = TRUE;
// Simplify it for optimal in-place use.
$this->simplify($form, $form_state);
return $form;
}
/**
* Initialize the form state and the entity before the first form build.
*/
protected function init(FormStateInterface $form_state, EntityInterface $entity, $field_name) {
// @todo Rather than special-casing $node->revision, invoke prepareEdit()
// once https://www.drupal.org/node/1863258 lands.
if ($entity->getEntityTypeId() == 'node') {
$node_type = $this->nodeTypeStorage->load($entity->bundle());
$entity->setNewRevision($node_type->shouldCreateNewRevision());
$entity->revision_log = NULL;
}
$form_state->set('entity', $entity);
$form_state->set('field_name', $field_name);
// Fetch the display used by the form. It is the display for the 'default'
// form mode, with only the current field visible.
$display = EntityFormDisplay::collectRenderDisplay($entity, 'default');
foreach ($display->getComponents() as $name => $options) {
if ($name != $field_name) {
$display->removeComponent($name);
}
}
$form_state->set('form_display', $display);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$entity = $this->buildEntity($form, $form_state);
$form_state->get('form_display')->validateFormValues($entity, $form, $form_state);
}
/**
* {@inheritdoc}
*
* Saves the entity with updated values for the edited field.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$entity = $this->buildEntity($form, $form_state);
$form_state->set('entity', $entity);
// Store entity in tempstore with its UUID as tempstore key.
$this->tempStoreFactory->get('quickedit')->set($entity->uuid(), $entity);
}
/**
* Returns a cloned entity containing updated field values.
*
* Calling code may then validate the returned entity, and if valid, transfer
* it back to the form state and save it.
*/
protected function buildEntity(array $form, FormStateInterface $form_state) {
/** @var $entity \Drupal\Core\Entity\EntityInterface */
$entity = clone $form_state->get('entity');
$field_name = $form_state->get('field_name');
$form_state->get('form_display')->extractFormValues($entity, $form, $form_state);
// @todo Refine automated log messages and abstract them to all entity
// types: https://www.drupal.org/node/1678002.
if ($entity->getEntityTypeId() == 'node' && $entity->isNewRevision() && $entity->revision_log->isEmpty()) {
$entity->revision_log = t('Updated the %field-name field through in-place editing.', ['%field-name' => $entity->get($field_name)->getFieldDefinition()->getLabel()]);
}
return $entity;
}
/**
* Simplifies the field edit form for in-place editing.
*
* This function:
* - Hides the field label inside the form, because JavaScript displays it
* outside the form.
* - Adjusts textarea elements to fit their content.
*
* @param array &$form
* A reference to an associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
protected function simplify(array &$form, FormStateInterface $form_state) {
$field_name = $form_state->get('field_name');
$widget_element =& $form[$field_name]['widget'];
// Hide the field label from displaying within the form, because JavaScript
// displays the equivalent label that was provided within an HTML data
// attribute of the field's display element outside of the form. Do this for
// widgets without child elements (like Option widgets) as well as for ones
// with per-delta elements. Skip single checkboxes, because their title is
// key to their UI. Also skip widgets with multiple subelements, because in
// that case, per-element labeling is informative.
$num_children = count(Element::children($widget_element));
if ($num_children == 0 && $widget_element['#type'] != 'checkbox') {
$widget_element['#title_display'] = 'invisible';
}
if ($num_children == 1 && isset($widget_element[0]['value'])) {
// @todo While most widgets name their primary element 'value', not all
// do, so generalize this.
$widget_element[0]['value']['#title_display'] = 'invisible';
}
// Adjust textarea elements to fit their content.
if (isset($widget_element[0]['value']['#type']) && $widget_element[0]['value']['#type'] == 'textarea') {
$lines = count(explode("\n", $widget_element[0]['value']['#default_value']));
$widget_element[0]['value']['#rows'] = $lines + 1;
}
}
}
@@ -0,0 +1,98 @@
<?php
namespace Drupal\quickedit;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\quickedit\Access\QuickEditEntityFieldAccessCheckInterface;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
/**
* Generates in-place editing metadata for an entity field.
*/
class MetadataGenerator implements MetadataGeneratorInterface {
/**
* An object that checks if a user has access to edit a given entity field.
*
* @var \Drupal\quickedit\Access\QuickEditEntityFieldAccessCheckInterface
*/
protected $accessChecker;
/**
* An object that determines which editor to attach to a given field.
*
* @var \Drupal\quickedit\EditorSelectorInterface
*/
protected $editorSelector;
/**
* The manager for editor plugins.
*
* @var \Drupal\Component\Plugin\PluginManagerInterface
*/
protected $editorManager;
/**
* Constructs a new MetadataGenerator.
*
* @param \Drupal\quickedit\Access\QuickEditEntityFieldAccessCheckInterface $access_checker
* An object that checks if a user has access to edit a given field.
* @param \Drupal\quickedit\EditorSelectorInterface $editor_selector
* An object that determines which editor to attach to a given field.
* @param \Drupal\Component\Plugin\PluginManagerInterface $editor_manager
* The manager for editor plugins.
*/
public function __construct(QuickEditEntityFieldAccessCheckInterface $access_checker, EditorSelectorInterface $editor_selector, PluginManagerInterface $editor_manager) {
$this->accessChecker = $access_checker;
$this->editorSelector = $editor_selector;
$this->editorManager = $editor_manager;
}
/**
* {@inheritdoc}
*/
public function generateEntityMetadata(EntityInterface $entity) {
return [
'label' => $entity->label(),
];
}
/**
* {@inheritdoc}
*/
public function generateFieldMetadata(FieldItemListInterface $items, $view_mode) {
$entity = $items->getEntity();
$field_name = $items->getFieldDefinition()->getName();
// Early-return if user does not have access.
$access = $this->accessChecker->accessEditEntityField($entity, $field_name);
if (!$access) {
return ['access' => FALSE];
}
// Early-return if no editor is available.
$formatter_id = EntityViewDisplay::collectRenderDisplay($entity, $view_mode)->getRenderer($field_name)->getPluginId();
$editor_id = $this->editorSelector->getEditor($formatter_id, $items);
if (!isset($editor_id)) {
return ['access' => FALSE];
}
// Gather metadata, allow the editor to add additional metadata of its own.
$label = $items->getFieldDefinition()->getLabel();
$editor = $this->editorManager->createInstance($editor_id);
$metadata = [
'label' => $label,
'access' => TRUE,
'editor' => $editor_id,
];
$custom_metadata = $editor->getMetadata($items);
if (count($custom_metadata)) {
$metadata['custom'] = $custom_metadata;
}
return $metadata;
}
}
@@ -0,0 +1,41 @@
<?php
namespace Drupal\quickedit;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
/**
* Interface for generating in-place editing metadata.
*/
interface MetadataGeneratorInterface {
/**
* Generates in-place editing metadata for an entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity, in the language in which one of its fields is being edited.
* @return array
* An array containing metadata with the following keys:
* - label: the user-visible label for the entity in the given language.
*/
public function generateEntityMetadata(EntityInterface $entity);
/**
* Generates in-place editing metadata for an entity field.
*
* @param \Drupal\Core\Field\FieldItemListInterface $items
* The field values to be in-place edited.
* @param string $view_mode
* The view mode the field should be rerendered in.
* @return array
* An array containing metadata with the following keys:
* - label: the user-visible label for the field.
* - access: whether the current user may edit the field or not.
* - editor: which editor should be used for the field.
* - aria: the ARIA label.
* - custom: (optional) any additional metadata that the editor provides.
*/
public function generateFieldMetadata(FieldItemListInterface $items, $view_mode);
}
@@ -0,0 +1,35 @@
<?php
namespace Drupal\quickedit\Plugin\InPlaceEditor;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\quickedit\Plugin\InPlaceEditorBase;
/**
* Defines the form in-place editor.
*
* @InPlaceEditor(
* id = "form"
* )
*/
class FormEditor extends InPlaceEditorBase {
/**
* {@inheritdoc}
*/
public function isCompatible(FieldItemListInterface $items) {
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getAttachments() {
return [
'library' => [
'quickedit/quickedit.inPlaceEditor.form',
],
];
}
}
@@ -0,0 +1,38 @@
<?php
namespace Drupal\quickedit\Plugin\InPlaceEditor;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\quickedit\Plugin\InPlaceEditorBase;
/**
* Defines the plain text in-place editor.
*
* @InPlaceEditor(
* id = "plain_text"
* )
*/
class PlainTextEditor extends InPlaceEditorBase {
/**
* {@inheritdoc}
*/
public function isCompatible(FieldItemListInterface $items) {
$field_definition = $items->getFieldDefinition();
// This editor is incompatible with multivalued fields.
return $field_definition->getFieldStorageDefinition()->getCardinality() == 1;
}
/**
* {@inheritdoc}
*/
public function getAttachments() {
return [
'library' => [
'quickedit/quickedit.inPlaceEditor.plainText',
],
];
}
}
@@ -0,0 +1,25 @@
<?php
namespace Drupal\quickedit\Plugin;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Field\FieldItemListInterface;
/**
* Defines a base in-place editor implementation.
*
* @see \Drupal\quickedit\Annotation\InPlaceEditor
* @see \Drupal\quickedit\Plugin\InPlaceEditorInterface
* @see \Drupal\quickedit\Plugin\InPlaceEditorManager
* @see plugin_api
*/
abstract class InPlaceEditorBase extends PluginBase implements InPlaceEditorInterface {
/**
* {@inheritdoc}
*/
public function getMetadata(FieldItemListInterface $items) {
return [];
}
}
@@ -0,0 +1,54 @@
<?php
namespace Drupal\quickedit\Plugin;
use Drupal\Component\Plugin\PluginInspectionInterface;
use Drupal\Core\Field\FieldItemListInterface;
/**
* Defines an interface for in-place editors plugins.
*
* @see \Drupal\quickedit\Annotation\InPlaceEditor
* @see \Drupal\quickedit\Plugin\InPlaceEditorBase
* @see \Drupal\quickedit\Plugin\InPlaceEditorManager
* @see plugin_api
*/
interface InPlaceEditorInterface extends PluginInspectionInterface {
/**
* Checks whether this in-place editor is compatible with a given field.
*
* @param \Drupal\Core\Field\FieldItemListInterface $items
* The field values to be in-place edited.
*
* @return bool
* TRUE if it is compatible, FALSE otherwise.
*/
public function isCompatible(FieldItemListInterface $items);
/**
* Generates metadata that is needed specifically for this editor.
*
* Will only be called by \Drupal\quickedit\MetadataGeneratorInterface::generate()
* when the passed in field & item values will use this editor.
*
* @param \Drupal\Core\Field\FieldItemListInterface $items
* The field values to be in-place edited.
*
* @return array
* A keyed array with metadata. Each key should be prefixed with the plugin
* ID of the editor.
*/
public function getMetadata(FieldItemListInterface $items);
/**
* Returns the attachments for this editor.
*
* @return array
* An array of attachments, for use with #attached.
*
* @see \Drupal\Core\Render\AttachmentsResponseProcessorInterface::processAttachments()
*/
public function getAttachments();
}
@@ -0,0 +1,38 @@
<?php
namespace Drupal\quickedit\Plugin;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
/**
* Provides an in-place editor manager.
*
* The 'form' in-place editor must always be available.
*
* @see \Drupal\quickedit\Annotation\InPlaceEditor
* @see \Drupal\quickedit\Plugin\InPlaceEditorBase
* @see \Drupal\quickedit\Plugin\InPlaceEditorInterface
* @see plugin_api
*/
class InPlaceEditorManager extends DefaultPluginManager {
/**
* Constructs a InPlaceEditorManager object.
*
* @param \Traversable $namespaces
* An object that implements \Traversable which contains the root paths
* keyed by the corresponding namespace to look for plugin implementations.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* Cache backend instance to use.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler to invoke the alter hook with.
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
parent::__construct('Plugin/InPlaceEditor', $namespaces, $module_handler, 'Drupal\quickedit\Plugin\InPlaceEditorInterface', 'Drupal\quickedit\Annotation\InPlaceEditor');
$this->alterInfo('quickedit_editor');
$this->setCacheBackend($cache_backend, 'quickedit:editor');
}
}
@@ -0,0 +1,337 @@
<?php
namespace Drupal\quickedit;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\quickedit\Ajax\FieldFormCommand;
use Drupal\quickedit\Ajax\FieldFormSavedCommand;
use Drupal\quickedit\Ajax\FieldFormValidationErrorsCommand;
use Drupal\quickedit\Ajax\EntitySavedCommand;
/**
* Returns responses for Quick Edit module routes.
*/
class QuickEditController extends ControllerBase {
/**
* The PrivateTempStore factory.
*
* @var \Drupal\Core\TempStore\PrivateTempStoreFactory
*/
protected $tempStoreFactory;
/**
* The in-place editing metadata generator.
*
* @var \Drupal\quickedit\MetadataGeneratorInterface
*/
protected $metadataGenerator;
/**
* The in-place editor selector.
*
* @var \Drupal\quickedit\EditorSelectorInterface
*/
protected $editorSelector;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The entity display repository service.
*
* @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
*/
protected $entityDisplayRepository;
/**
* The entity repository.
*
* @var \Drupal\Core\Entity\EntityRepositoryInterface
*/
protected $entityRepository;
/**
* Constructs a new QuickEditController.
*
* @param \Drupal\Core\TempStore\PrivateTempStoreFactory $temp_store_factory
* The PrivateTempStore factory.
* @param \Drupal\quickedit\MetadataGeneratorInterface $metadata_generator
* The in-place editing metadata generator.
* @param \Drupal\quickedit\EditorSelectorInterface $editor_selector
* The in-place editor selector.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
* The entity display repository service.
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository.
*/
public function __construct(PrivateTempStoreFactory $temp_store_factory, MetadataGeneratorInterface $metadata_generator, EditorSelectorInterface $editor_selector, RendererInterface $renderer, EntityDisplayRepositoryInterface $entity_display_repository, EntityRepositoryInterface $entity_repository) {
$this->tempStoreFactory = $temp_store_factory;
$this->metadataGenerator = $metadata_generator;
$this->editorSelector = $editor_selector;
$this->renderer = $renderer;
if (!$entity_display_repository) {
@trigger_error('The entity_display.repository service must be passed to QuickEditController::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
$entity_display_repository = \Drupal::service('entity_display.repository');
}
$this->entityDisplayRepository = $entity_display_repository;
if (!$entity_repository) {
@trigger_error('The entity.repository service must be passed to QuickEditController::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
$entity_repository = \Drupal::service('entity.repository');
}
$this->entityRepository = $entity_repository;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('tempstore.private'),
$container->get('quickedit.metadata.generator'),
$container->get('quickedit.editor.selector'),
$container->get('renderer'),
$container->get('entity_display.repository'),
$container->get('entity.repository')
);
}
/**
* Returns the metadata for a set of fields.
*
* Given a list of field quick edit IDs as POST parameters, run access checks
* on the entity and field level to determine whether the current user may
* edit them. Also retrieves other metadata.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* The JSON response.
*/
public function metadata(Request $request) {
$fields = $request->request->get('fields');
if (!isset($fields)) {
throw new NotFoundHttpException();
}
$entities = $request->request->get('entities');
$metadata = [];
foreach ($fields as $field) {
list($entity_type, $entity_id, $field_name, $langcode, $view_mode) = explode('/', $field);
// Load the entity.
if (!$entity_type || !$this->entityTypeManager()->getDefinition($entity_type)) {
throw new NotFoundHttpException();
}
$entity = $this->entityTypeManager()->getStorage($entity_type)->load($entity_id);
if (!$entity) {
throw new NotFoundHttpException();
}
// Validate the field name and language.
if (!$field_name || !$entity->hasField($field_name)) {
throw new NotFoundHttpException();
}
if (!$langcode || !$entity->hasTranslation($langcode)) {
throw new NotFoundHttpException();
}
$entity = $entity->getTranslation($langcode);
// If the entity information for this field is requested, include it.
$entity_id = $entity->getEntityTypeId() . '/' . $entity_id;
if (is_array($entities) && in_array($entity_id, $entities) && !isset($metadata[$entity_id])) {
$metadata[$entity_id] = $this->metadataGenerator->generateEntityMetadata($entity);
}
$metadata[$field] = $this->metadataGenerator->generateFieldMetadata($entity->get($field_name), $view_mode);
}
return new JsonResponse($metadata);
}
/**
* Returns AJAX commands to load in-place editors' attachments.
*
* Given a list of in-place editor IDs as POST parameters, render AJAX
* commands to load those in-place editors.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* The Ajax response.
*/
public function attachments(Request $request) {
$response = new AjaxResponse();
$editors = $request->request->get('editors');
if (!isset($editors)) {
throw new NotFoundHttpException();
}
$response->setAttachments($this->editorSelector->getEditorAttachments($editors));
return $response;
}
/**
* Returns a single field edit form as an Ajax response.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity being edited.
* @param string $field_name
* The name of the field that is being edited.
* @param string $langcode
* The name of the language for which the field is being edited.
* @param string $view_mode_id
* The view mode the field should be rerendered in.
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request object containing the search string.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* The Ajax response.
*/
public function fieldForm(EntityInterface $entity, $field_name, $langcode, $view_mode_id, Request $request) {
$response = new AjaxResponse();
// Replace entity with PrivateTempStore copy if available and not resetting,
// init PrivateTempStore copy otherwise.
$tempstore_entity = $this->tempStoreFactory->get('quickedit')->get($entity->uuid());
if ($tempstore_entity && $request->request->get('reset') !== 'true') {
$entity = $tempstore_entity;
}
else {
$this->tempStoreFactory->get('quickedit')->set($entity->uuid(), $entity);
}
$form_state = (new FormState())
->set('langcode', $langcode)
->disableRedirect()
->addBuildInfo('args', [$entity, $field_name]);
$form = $this->formBuilder()->buildForm('Drupal\quickedit\Form\QuickEditFieldForm', $form_state);
if ($form_state->isExecuted()) {
// The form submission saved the entity in PrivateTempStore. Return the
// updated view of the field from the PrivateTempStore copy.
$entity = $this->tempStoreFactory->get('quickedit')->get($entity->uuid());
// Closure to render the field given a view mode.
$render_field_in_view_mode = function ($view_mode_id) use ($entity, $field_name, $langcode) {
return $this->renderField($entity, $field_name, $langcode, $view_mode_id);
};
// Re-render the updated field.
$output = $render_field_in_view_mode($view_mode_id);
// Re-render the updated field for other view modes (i.e. for other
// instances of the same logical field on the user's page).
$other_view_mode_ids = $request->request->get('other_view_modes') ?: [];
$other_view_modes = array_map($render_field_in_view_mode, array_combine($other_view_mode_ids, $other_view_mode_ids));
$response->addCommand(new FieldFormSavedCommand($output, $other_view_modes));
}
else {
$output = $this->renderer->renderRoot($form);
// When working with a hidden form, we don't want its CSS/JS to be loaded.
if ($request->request->get('nocssjs') !== 'true') {
$response->setAttachments($form['#attached']);
}
$response->addCommand(new FieldFormCommand($output));
$errors = $form_state->getErrors();
if (count($errors)) {
$status_messages = [
'#type' => 'status_messages',
];
$response->addCommand(new FieldFormValidationErrorsCommand($this->renderer->renderRoot($status_messages)));
}
}
return $response;
}
/**
* Renders a field.
*
* If the view mode ID is not an Entity Display view mode ID, then the field
* was rendered using a custom render pipeline (not the Entity/Field API
* render pipeline).
*
* An example could be Views' render pipeline. In that case, the view mode ID
* would probably contain the View's ID, display and the row index.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity being edited.
* @param string $field_name
* The name of the field that is being edited.
* @param string $langcode
* The name of the language for which the field is being edited.
* @param string $view_mode_id
* The view mode the field should be rerendered in. Either an Entity Display
* view mode ID, or a custom one. See hook_quickedit_render_field().
*
* @return \Drupal\Component\Render\MarkupInterface
* Rendered HTML.
*
* @see hook_quickedit_render_field()
*/
protected function renderField(EntityInterface $entity, $field_name, $langcode, $view_mode_id) {
$entity_view_mode_ids = array_keys($this->entityDisplayRepository->getViewModes($entity->getEntityTypeId()));
if (in_array($view_mode_id, $entity_view_mode_ids)) {
$entity = $this->entityRepository->getTranslationFromContext($entity, $langcode);
$output = $entity->get($field_name)->view($view_mode_id);
}
else {
// Each part of a custom (non-Entity Display) view mode ID is separated
// by a dash; the first part must be the module name.
$mode_id_parts = explode('-', $view_mode_id, 2);
$module = reset($mode_id_parts);
$args = [$entity, $field_name, $view_mode_id, $langcode];
$output = $this->moduleHandler()->invoke($module, 'quickedit_render_field', $args);
}
return $this->renderer->renderRoot($output);
}
/**
* Saves an entity into the database, from PrivateTempStore.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity being edited.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* The Ajax response.
*/
public function entitySave(EntityInterface $entity) {
// Take the entity from PrivateTempStore and save in entity storage.
// fieldForm() ensures that the PrivateTempStore copy exists ahead.
$tempstore = $this->tempStoreFactory->get('quickedit');
$tempstore->get($entity->uuid())->save();
$tempstore->delete($entity->uuid());
// Return information about the entity that allows a front end application
// to identify it.
$output = [
'entity_type' => $entity->getEntityTypeId(),
'entity_id' => $entity->id(),
];
// Respond to client that the entity was saved properly.
$response = new AjaxResponse();
$response->addCommand(new EntitySavedCommand($output));
return $response;
}
}