Move into nested docroot

This commit is contained in:
Rob Davies 2017-02-13 15:31:17 +00:00
parent 83a0d3a149
commit c8b70abde9
13405 changed files with 0 additions and 0 deletions

View file

@ -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 editing entity fields.
*/
class EditEntityFieldAccessCheck implements AccessInterface, EditEntityFieldAccessCheckInterface {
/**
* 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;
}
}

View file

@ -0,0 +1,25 @@
<?php
namespace Drupal\quickedit\Access;
use Drupal\Core\Entity\EntityInterface;
/**
* Access check for editing entity fields.
*/
interface EditEntityFieldAccessCheckInterface {
/**
* 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);
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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 = array()) {
parent::__construct('quickeditFieldFormSaved', $data);
$this->other_view_modes = $other_view_modes;
}
/**
* {@inheritdoc}
*/
public function render() {
return array(
'command' => $this->command,
'data' => $this->data,
'other_view_modes' => $this->other_view_modes,
);
}
}

View file

@ -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);
}
}

View file

@ -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;
}

View file

@ -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 = array($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 = array();
$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);
}
}

View file

@ -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);
}

View file

@ -0,0 +1,233 @@
<?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\user\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Builds and process a form for editing a single entity field.
*/
class QuickEditFieldForm extends FormBase {
/**
* Stores the tempstore factory.
*
* @var \Drupal\user\PrivateTempStoreFactory
*/
protected $tempStoreFactory;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The node type storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeTypeStorage;
/**
* The typed data validator.
*
* @var \Symfony\Component\Validator\Validator\ValidatorInterface
*/
protected $validator;
/**
* Constructs a new EditFieldForm.
*
* @param \Drupal\user\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.
* @param \Symfony\Component\Validator\Validator\ValidatorInterface $validator
* The typed data validator service.
*/
public function __construct(PrivateTempStoreFactory $temp_store_factory, ModuleHandlerInterface $module_handler, EntityStorageInterface $node_type_storage, ValidatorInterface $validator) {
$this->moduleHandler = $module_handler;
$this->nodeTypeStorage = $node_type_storage;
$this->tempStoreFactory = $temp_store_factory;
$this->validator = $validator;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('user.private_tempstore'),
$container->get('module_handler'),
$container->get('entity.manager')->getStorage('node_type'),
$container->get('typed_data_manager')->getValidator()
);
}
/**
* {@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'] = array(
'#type' => 'hidden',
'#value' => $entity->getChangedTime(),
);
}
// Add a submit button. Give it a class for easy JavaScript targeting.
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#attributes' => array('class' => array('quickedit-form-submit')),
);
// 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->isNewRevision());
$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.', array('%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;
}
}
}

View file

@ -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\EditEntityFieldAccessCheckInterface;
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\EditEntityFieldAccessCheckInterface
*/
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\EditEntityFieldAccessCheckInterface $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(EditEntityFieldAccessCheckInterface $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 array(
'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 array('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 array('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 = array(
'label' => $label,
'access' => TRUE,
'editor' => $editor_id,
);
$custom_metadata = $editor->getMetadata($items);
if (count($custom_metadata)) {
$metadata['custom'] = $custom_metadata;
}
return $metadata;
}
}

View file

@ -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);
}

View file

@ -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 array(
'library' => array(
'quickedit/quickedit.inPlaceEditor.form',
),
);
}
}

View file

@ -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 array(
'library' => array(
'quickedit/quickedit.inPlaceEditor.plainText',
),
);
}
}

View file

@ -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}
*/
function getMetadata(FieldItemListInterface $items) {
return array();
}
}

View file

@ -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();
}

View file

@ -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');
}
}

View file

@ -0,0 +1,305 @@
<?php
namespace Drupal\quickedit;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormState;
use Drupal\Core\Render\RendererInterface;
use Drupal\user\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\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\user\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;
/**
* Constructs a new QuickEditController.
*
* @param \Drupal\user\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.
*/
public function __construct(PrivateTempStoreFactory $temp_store_factory, MetadataGeneratorInterface $metadata_generator, EditorSelectorInterface $editor_selector, RendererInterface $renderer) {
$this->tempStoreFactory = $temp_store_factory;
$this->metadataGenerator = $metadata_generator;
$this->editorSelector = $editor_selector;
$this->renderer = $renderer;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('user.private_tempstore'),
$container->get('quickedit.metadata.generator'),
$container->get('quickedit.editor.selector'),
$container->get('renderer')
);
}
/**
* 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 = array();
foreach ($fields as $field) {
list($entity_type, $entity_id, $field_name, $langcode, $view_mode) = explode('/', $field);
// Load the entity.
if (!$entity_type || !$this->entityManager()->getDefinition($entity_type)) {
throw new NotFoundHttpException();
}
$entity = $this->entityManager()->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') ?: array();
$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 = array(
'#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->entityManager()->getViewModes($entity->getEntityTypeId()));
if (in_array($view_mode_id, $entity_view_mode_ids)) {
$entity = \Drupal::entityManager()->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 = array($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 = array(
'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;
}
}

View file

@ -0,0 +1,215 @@
<?php
namespace Drupal\quickedit\Tests;
use Drupal\Component\Serialization\Json;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\simpletest\WebTestBase;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\taxonomy\Entity\Term;
/**
* Tests in-place editing of autocomplete tags.
*
* @group quickedit
*/
class QuickEditAutocompleteTermTest extends WebTestBase {
use EntityReferenceTestTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('node', 'taxonomy', 'quickedit');
/**
* Stores the node used for the tests.
*
* @var \Drupal\node\NodeInterface
*/
protected $node;
/**
* Stores the vocabulary used in the tests.
*
* @var \Drupal\taxonomy\VocabularyInterface
*/
protected $vocabulary;
/**
* Stores the first term used in the tests.
*
* @var \Drupal\taxonomy\TermInterface
*/
protected $term1;
/**
* Stores the second term used in the tests.
*
* @var \Drupal\taxonomy\TermInterface
*/
protected $term2;
/**
* Stores the field name for the autocomplete field.
*
* @var string
*/
protected $fieldName;
/**
* An user with permissions to access in-place editor.
*
* @var \Drupal\user\UserInterface
*/
protected $editorUser;
protected function setUp() {
parent::setUp();
$this->drupalCreateContentType(array(
'type' => 'article',
));
// Create the vocabulary for the tag field.
$this->vocabulary = Vocabulary::create([
'name' => 'quickedit testing tags',
'vid' => 'quickedit_testing_tags',
]);
$this->vocabulary->save();
$this->fieldName = 'field_' . $this->vocabulary->id();
$handler_settings = array(
'target_bundles' => array(
$this->vocabulary->id() => $this->vocabulary->id(),
),
'auto_create' => TRUE,
);
$this->createEntityReferenceField('node', 'article', $this->fieldName, 'Tags', 'taxonomy_term', 'default', $handler_settings, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
entity_get_form_display('node', 'article', 'default')
->setComponent($this->fieldName, [
'type' => 'entity_reference_autocomplete_tags',
'weight' => -4,
])
->save();
entity_get_display('node', 'article', 'default')
->setComponent($this->fieldName, [
'type' => 'entity_reference_label',
'weight' => 10,
])
->save();
entity_get_display('node', 'article', 'teaser')
->setComponent($this->fieldName, [
'type' => 'entity_reference_label',
'weight' => 10,
])
->save();
$this->term1 = $this->createTerm();
$this->term2 = $this->createTerm();
$node = array();
$node['type'] = 'article';
$node[$this->fieldName][]['target_id'] = $this->term1->id();
$node[$this->fieldName][]['target_id'] = $this->term2->id();
$this->node = $this->drupalCreateNode($node);
$this->editorUser = $this->drupalCreateUser(['access content', 'create article content', 'edit any article content', 'access in-place editing']);
}
/**
* Tests Quick Edit autocomplete term behavior.
*/
public function testAutocompleteQuickEdit() {
$this->drupalLogin($this->editorUser);
$quickedit_uri = 'quickedit/form/node/' . $this->node->id() . '/' . $this->fieldName . '/' . $this->node->language()->getId() . '/full';
$post = array('nocssjs' => 'true') + $this->getAjaxPageStatePostData();
$response = $this->drupalPost($quickedit_uri, '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$ajax_commands = Json::decode($response);
// Prepare form values for submission. drupalPostAJAX() is not suitable for
// handling pages with JSON responses, so we need our own solution here.
$form_tokens_found = preg_match('/\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match) && preg_match('/\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
$this->assertTrue($form_tokens_found, 'Form tokens found in output.');
if ($form_tokens_found) {
$post = array(
'form_id' => 'quickedit_field_form',
'form_token' => $token_match[1],
'form_build_id' => $build_id_match[1],
$this->fieldName . '[target_id]' => implode(', ', array($this->term1->getName(), 'new term', $this->term2->getName())),
'op' => t('Save'),
);
// Submit field form and check response. Should render back all the terms.
$response = $this->drupalPost($quickedit_uri, '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->setRawContent($ajax_commands[0]['data']);
$this->assertLink($this->term1->getName());
$this->assertLink($this->term2->getName());
$this->assertText('new term');
$this->assertNoLink('new term');
// Load the form again, which should now get it back from
// PrivateTempStore.
$quickedit_uri = 'quickedit/form/node/' . $this->node->id() . '/' . $this->fieldName . '/' . $this->node->language()->getId() . '/full';
$post = array('nocssjs' => 'true') + $this->getAjaxPageStatePostData();
$response = $this->drupalPost($quickedit_uri, '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$ajax_commands = Json::decode($response);
// The AjaxResponse's first command is an InsertCommand which contains
// the form to edit the taxonomy term field, it should contain all three
// taxonomy terms, including the one that has just been newly created and
// which is not yet stored.
$this->setRawContent($ajax_commands[0]['data']);
$expected = array(
$this->term1->getName() . ' (' . $this->term1->id() . ')',
'new term',
$this->term2->getName() . ' (' . $this->term2->id() . ')',
);
$this->assertFieldByName($this->fieldName . '[target_id]', implode(', ', $expected));
// Save the entity.
$post = array('nocssjs' => 'true');
$response = $this->drupalPostWithFormat('quickedit/entity/node/' . $this->node->id(), 'json', $post);
$this->assertResponse(200);
// The full node display should now link to all entities, with the new
// one created in the database as well.
$this->drupalGet('node/' . $this->node->id());
$this->assertLink($this->term1->getName());
$this->assertLink($this->term2->getName());
$this->assertLink('new term');
}
}
/**
* Returns a new term with random name and description in $this->vocabulary.
*
* @return \Drupal\taxonomy\TermInterface
* The created taxonomy term.
*/
protected function createTerm() {
$filter_formats = filter_formats();
$format = array_pop($filter_formats);
$term = Term::create([
'name' => $this->randomMachineName(),
'description' => $this->randomMachineName(),
// Use the first available text format.
'format' => $format->id(),
'vid' => $this->vocabulary->id(),
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
]);
$term->save();
return $term;
}
}

View file

@ -0,0 +1,569 @@
<?php
namespace Drupal\quickedit\Tests;
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\Unicode;
use Drupal\block_content\Entity\BlockContent;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\simpletest\WebTestBase;
use Drupal\filter\Entity\FilterFormat;
/**
* Tests loading of in-place editing functionality and lazy loading of its
* in-place editors.
*
* @group quickedit
*/
class QuickEditLoadingTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array(
'contextual',
'quickedit',
'filter',
'node',
'image',
);
/**
* An user with permissions to create and edit articles.
*
* @var \Drupal\user\UserInterface
*/
protected $authorUser;
/**
* A author user with permissions to access in-place editor.
*
* @var \Drupal\user\UserInterface
*/
protected $editorUser;
protected function setUp() {
parent::setUp();
// Create a text format.
$filtered_html_format = FilterFormat::create(array(
'format' => 'filtered_html',
'name' => 'Filtered HTML',
'weight' => 0,
'filters' => array(),
));
$filtered_html_format->save();
// Create a node type.
$this->drupalCreateContentType(array(
'type' => 'article',
'name' => 'Article',
));
// Set the node type to initially not have revisions.
// Testing with revisions will be done later.
$node_type = NodeType::load('article');
$node_type->setNewRevision(FALSE);
$node_type->save();
// Create one node of the above node type using the above text format.
$this->drupalCreateNode(array(
'type' => 'article',
'body' => array(
0 => array(
'value' => '<p>How are you?</p>',
'format' => 'filtered_html',
)
),
'revision_log' => $this->randomString(),
));
// Create 2 users, the only difference being the ability to use in-place
// editing
$basic_permissions = array('access content', 'create article content', 'edit any article content', 'use text format filtered_html', 'access contextual links');
$this->authorUser = $this->drupalCreateUser($basic_permissions);
$this->editorUser = $this->drupalCreateUser(array_merge($basic_permissions, array('access in-place editing')));
}
/**
* Test the loading of Quick Edit when a user doesn't have access to it.
*/
public function testUserWithoutPermission() {
$this->drupalLogin($this->authorUser);
$this->drupalGet('node/1');
// Library and in-place editors.
$this->assertNoRaw('core/modules/quickedit/js/quickedit.js', 'Quick Edit library not loaded.');
$this->assertNoRaw('core/modules/quickedit/js/editors/formEditor.js', "'form' in-place editor not loaded.");
// HTML annotation does not exist for users without permission to in-place
// edit.
$this->assertNoRaw('data-quickedit-entity-id="node/1"');
$this->assertNoRaw('data-quickedit-field-id="node/1/body/en/full"');
// Retrieving the metadata should result in an empty 403 response.
$post = array('fields[0]' => 'node/1/body/en/full');
$response = $this->drupalPostWithFormat(Url::fromRoute('quickedit.metadata'), 'json', $post);
$this->assertIdentical('{"message":""}', $response);
$this->assertResponse(403);
// Quick Edit's JavaScript would SearchRankingTestnever hit these endpoints if the metadata
// was empty as above, but we need to make sure that malicious users aren't
// able to use any of the other endpoints either.
$post = array('editors[0]' => 'form') + $this->getAjaxPageStatePostData();
$response = $this->drupalPost('quickedit/attachments', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertIdentical('{}', $response);
$this->assertResponse(403);
$post = array('nocssjs' => 'true') + $this->getAjaxPageStatePostData();
$response = $this->drupalPost('quickedit/form/' . 'node/1/body/en/full', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertIdentical('{}', $response);
$this->assertResponse(403);
$edit = array();
$edit['form_id'] = 'quickedit_field_form';
$edit['form_token'] = 'xIOzMjuc-PULKsRn_KxFn7xzNk5Bx7XKXLfQfw1qOnA';
$edit['form_build_id'] = 'form-kVmovBpyX-SJfTT5kY0pjTV35TV-znor--a64dEnMR8';
$edit['body[0][summary]'] = '';
$edit['body[0][value]'] = '<p>Malicious content.</p>';
$edit['body[0][format]'] = 'filtered_html';
$edit['op'] = t('Save');
$response = $this->drupalPost('quickedit/form/' . 'node/1/body/en/full', '', $edit, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertIdentical('{}', $response);
$this->assertResponse(403);
$post = array('nocssjs' => 'true');
$response = $this->drupalPostWithFormat('quickedit/entity/' . 'node/1', 'json', $post);
$this->assertIdentical('{"message":""}', $response);
$this->assertResponse(403);
}
/**
* Tests the loading of Quick Edit when a user does have access to it.
*
* Also ensures lazy loading of in-place editors works.
*/
public function testUserWithPermission() {
$this->drupalLogin($this->editorUser);
$this->drupalGet('node/1');
// Library and in-place editors.
$settings = $this->getDrupalSettings();
$libraries = explode(',', $settings['ajaxPageState']['libraries']);
$this->assertTrue(in_array('quickedit/quickedit', $libraries), 'Quick Edit library loaded.');
$this->assertFalse(in_array('quickedit/quickedit.inPlaceEditor.form', $libraries), "'form' in-place editor not loaded.");
// HTML annotation must always exist (to not break the render cache).
$this->assertRaw('data-quickedit-entity-id="node/1"');
$this->assertRaw('data-quickedit-field-id="node/1/body/en/full"');
// There should be only one revision so far.
$node = Node::load(1);
$vids = \Drupal::entityManager()->getStorage('node')->revisionIds($node);
$this->assertIdentical(1, count($vids), 'The node has only one revision.');
$original_log = $node->revision_log->value;
// Retrieving the metadata should result in a 200 JSON response.
$htmlPageDrupalSettings = $this->drupalSettings;
$post = array('fields[0]' => 'node/1/body/en/full');
$response = $this->drupalPostWithFormat('quickedit/metadata', 'json', $post);
$this->assertResponse(200);
$expected = array(
'node/1/body/en/full' => array(
'label' => 'Body',
'access' => TRUE,
'editor' => 'form',
)
);
$this->assertIdentical(Json::decode($response), $expected, 'The metadata HTTP request answers with the correct JSON response.');
// Restore drupalSettings to build the next requests; simpletest wipes them
// after a JSON response.
$this->drupalSettings = $htmlPageDrupalSettings;
// Retrieving the attachments should result in a 200 response, containing:
// 1. a settings command with useless metadata: AjaxController is dumb
// 2. an insert command that loads the required in-place editors
$post = array('editors[0]' => 'form') + $this->getAjaxPageStatePostData();
$response = $this->drupalPost('quickedit/attachments', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$ajax_commands = Json::decode($response);
$this->assertIdentical(2, count($ajax_commands), 'The attachments HTTP request results in two AJAX commands.');
// First command: settings.
$this->assertIdentical('settings', $ajax_commands[0]['command'], 'The first AJAX command is a settings command.');
// Second command: insert libraries into DOM.
$this->assertIdentical('insert', $ajax_commands[1]['command'], 'The second AJAX command is an append command.');
$this->assertTrue(in_array('quickedit/quickedit.inPlaceEditor.form', explode(',', $ajax_commands[0]['settings']['ajaxPageState']['libraries'])), 'The quickedit.inPlaceEditor.form library is loaded.');
// Retrieving the form for this field should result in a 200 response,
// containing only a quickeditFieldForm command.
$post = array('nocssjs' => 'true', 'reset' => 'true') + $this->getAjaxPageStatePostData();
$response = $this->drupalPost('quickedit/form/' . 'node/1/body/en/full', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(1, count($ajax_commands), 'The field form HTTP request results in one AJAX command.');
$this->assertIdentical('quickeditFieldForm', $ajax_commands[0]['command'], 'The first AJAX command is a quickeditFieldForm command.');
$this->assertIdentical('<form ', Unicode::substr($ajax_commands[0]['data'], 0, 6), 'The quickeditFieldForm command contains a form.');
// Prepare form values for submission. drupalPostAjaxForm() is not suitable
// for handling pages with JSON responses, so we need our own solution here.
$form_tokens_found = preg_match('/\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match) && preg_match('/\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
$this->assertTrue($form_tokens_found, 'Form tokens found in output.');
if ($form_tokens_found) {
$edit = array(
'body[0][summary]' => '',
'body[0][value]' => '<p>Fine thanks.</p>',
'body[0][format]' => 'filtered_html',
'op' => t('Save'),
);
$post = array(
'form_id' => 'quickedit_field_form',
'form_token' => $token_match[1],
'form_build_id' => $build_id_match[1],
);
$post += $edit + $this->getAjaxPageStatePostData();
// Submit field form and check response. This should store the updated
// entity in PrivateTempStore on the server.
$response = $this->drupalPost('quickedit/form/' . 'node/1/body/en/full', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(1, count($ajax_commands), 'The field form HTTP request results in one AJAX command.');
$this->assertIdentical('quickeditFieldFormSaved', $ajax_commands[0]['command'], 'The first AJAX command is a quickeditFieldFormSaved command.');
$this->assertTrue(strpos($ajax_commands[0]['data'], 'Fine thanks.'), 'Form value saved and printed back.');
$this->assertIdentical($ajax_commands[0]['other_view_modes'], array(), 'Field was not rendered in any other view mode.');
// Ensure the text on the original node did not change yet.
$this->drupalGet('node/1');
$this->assertText('How are you?');
// Save the entity by moving the PrivateTempStore values to entity storage.
$post = array('nocssjs' => 'true');
$response = $this->drupalPostWithFormat('quickedit/entity/' . 'node/1', 'json', $post);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(1, count($ajax_commands), 'The entity submission HTTP request results in one AJAX command.');
$this->assertIdentical('quickeditEntitySaved', $ajax_commands[0]['command'], 'The first AJAX command is a quickeditEntitySaved command.');
$this->assertIdentical($ajax_commands[0]['data']['entity_type'], 'node', 'Saved entity is of type node.');
$this->assertIdentical($ajax_commands[0]['data']['entity_id'], '1', 'Entity id is 1.');
// Ensure the text on the original node did change.
$this->drupalGet('node/1');
$this->assertText('Fine thanks.');
// Ensure no new revision was created and the log message is unchanged.
$node = Node::load(1);
$vids = \Drupal::entityManager()->getStorage('node')->revisionIds($node);
$this->assertIdentical(1, count($vids), 'The node has only one revision.');
$this->assertIdentical($original_log, $node->revision_log->value, 'The revision log message is unchanged.');
// Now configure this node type to create new revisions automatically,
// then again retrieve the field form, fill it, submit it (so it ends up
// in PrivateTempStore) and then save the entity. Now there should be two
// revisions.
$node_type = NodeType::load('article');
$node_type->setNewRevision(TRUE);
$node_type->save();
// Retrieve field form.
$post = array('nocssjs' => 'true', 'reset' => 'true');
$response = $this->drupalPost('quickedit/form/' . 'node/1/body/en/full', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(1, count($ajax_commands), 'The field form HTTP request results in one AJAX command.');
$this->assertIdentical('quickeditFieldForm', $ajax_commands[0]['command'], 'The first AJAX command is a quickeditFieldForm command.');
$this->assertIdentical('<form ', Unicode::substr($ajax_commands[0]['data'], 0, 6), 'The quickeditFieldForm command contains a form.');
// Submit field form.
preg_match('/\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match);
preg_match('/\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
$edit['body[0][value]'] = '<p>kthxbye</p>';
$post = array(
'form_id' => 'quickedit_field_form',
'form_token' => $token_match[1],
'form_build_id' => $build_id_match[1],
);
$post += $edit + $this->getAjaxPageStatePostData();
$response = $this->drupalPost('quickedit/form/' . 'node/1/body/en/full', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(1, count($ajax_commands), 'The field form HTTP request results in one AJAX command.');
$this->assertIdentical('quickeditFieldFormSaved', $ajax_commands[0]['command'], 'The first AJAX command is an quickeditFieldFormSaved command.');
$this->assertTrue(strpos($ajax_commands[0]['data'], 'kthxbye'), 'Form value saved and printed back.');
// Save the entity.
$post = array('nocssjs' => 'true');
$response = $this->drupalPostWithFormat('quickedit/entity/' . 'node/1', 'json', $post);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(1, count($ajax_commands));
$this->assertIdentical('quickeditEntitySaved', $ajax_commands[0]['command'], 'The first AJAX command is an quickeditEntitySaved command.');
$this->assertEqual($ajax_commands[0]['data'], ['entity_type' => 'node', 'entity_id' => 1], 'Updated entity type and ID returned');
// Test that a revision was created with the correct log message.
$vids = \Drupal::entityManager()->getStorage('node')->revisionIds(Node::load(1));
$this->assertIdentical(2, count($vids), 'The node has two revisions.');
$revision = node_revision_load($vids[0]);
$this->assertIdentical($original_log, $revision->revision_log->value, 'The first revision log message is unchanged.');
$revision = node_revision_load($vids[1]);
$this->assertIdentical('Updated the <em class="placeholder">Body</em> field through in-place editing.', $revision->revision_log->value, 'The second revision log message was correctly generated by Quick Edit module.');
}
}
/**
* Tests the loading of Quick Edit for the title base field.
*/
public function testTitleBaseField() {
$this->drupalLogin($this->editorUser);
$this->drupalGet('node/1');
// Ensure that the full page title is actually in-place editable
$node = Node::load(1);
$elements = $this->xpath('//h1/span[@data-quickedit-field-id="node/1/title/en/full" and normalize-space(text())=:title]', array(':title' => $node->label()));
$this->assertTrue(!empty($elements), 'Title with data-quickedit-field-id attribute found.');
// Retrieving the metadata should result in a 200 JSON response.
$htmlPageDrupalSettings = $this->drupalSettings;
$post = array('fields[0]' => 'node/1/title/en/full');
$response = $this->drupalPostWithFormat('quickedit/metadata', 'json', $post);
$this->assertResponse(200);
$expected = array(
'node/1/title/en/full' => array(
'label' => 'Title',
'access' => TRUE,
'editor' => 'plain_text',
)
);
$this->assertIdentical(Json::decode($response), $expected, 'The metadata HTTP request answers with the correct JSON response.');
// Restore drupalSettings to build the next requests; simpletest wipes them
// after a JSON response.
$this->drupalSettings = $htmlPageDrupalSettings;
// Retrieving the form for this field should result in a 200 response,
// containing only a quickeditFieldForm command.
$post = array('nocssjs' => 'true', 'reset' => 'true') + $this->getAjaxPageStatePostData();
$response = $this->drupalPost('quickedit/form/' . 'node/1/title/en/full', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(1, count($ajax_commands), 'The field form HTTP request results in one AJAX command.');
$this->assertIdentical('quickeditFieldForm', $ajax_commands[0]['command'], 'The first AJAX command is a quickeditFieldForm command.');
$this->assertIdentical('<form ', Unicode::substr($ajax_commands[0]['data'], 0, 6), 'The quickeditFieldForm command contains a form.');
// Prepare form values for submission. drupalPostAjaxForm() is not suitable
// for handling pages with JSON responses, so we need our own solution
// here.
$form_tokens_found = preg_match('/\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match) && preg_match('/\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
$this->assertTrue($form_tokens_found, 'Form tokens found in output.');
if ($form_tokens_found) {
$edit = array(
'title[0][value]' => 'Obligatory question',
'op' => t('Save'),
);
$post = array(
'form_id' => 'quickedit_field_form',
'form_token' => $token_match[1],
'form_build_id' => $build_id_match[1],
);
$post += $edit + $this->getAjaxPageStatePostData();
// Submit field form and check response. This should store the
// updated entity in PrivateTempStore on the server.
$response = $this->drupalPost('quickedit/form/' . 'node/1/title/en/full', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(1, count($ajax_commands), 'The field form HTTP request results in one AJAX command.');
$this->assertIdentical('quickeditFieldFormSaved', $ajax_commands[0]['command'], 'The first AJAX command is a quickeditFieldFormSaved command.');
$this->assertTrue(strpos($ajax_commands[0]['data'], 'Obligatory question'), 'Form value saved and printed back.');
// Ensure the text on the original node did not change yet.
$this->drupalGet('node/1');
$this->assertNoText('Obligatory question');
// Save the entity by moving the PrivateTempStore values to entity storage.
$post = array('nocssjs' => 'true');
$response = $this->drupalPostWithFormat('quickedit/entity/' . 'node/1', 'json', $post);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(1, count($ajax_commands), 'The entity submission HTTP request results in one AJAX command.');
$this->assertIdentical('quickeditEntitySaved', $ajax_commands[0]['command'], 'The first AJAX command is n quickeditEntitySaved command.');
$this->assertIdentical($ajax_commands[0]['data']['entity_type'], 'node', 'Saved entity is of type node.');
$this->assertIdentical($ajax_commands[0]['data']['entity_id'], '1', 'Entity id is 1.');
// Ensure the text on the original node did change.
$this->drupalGet('node/1');
$this->assertText('Obligatory question');
}
}
/**
* Tests that Quick Edit doesn't make fields rendered with display options
* editable.
*/
public function testDisplayOptions() {
$node = Node::load('1');
$display_settings = array(
'label' => 'inline',
);
$build = $node->body->view($display_settings);
$output = \Drupal::service('renderer')->renderRoot($build);
$this->assertFalse(strpos($output, 'data-quickedit-field-id'), 'data-quickedit-field-id attribute not added when rendering field using dynamic display options.');
}
/**
* Tests that Quick Edit works with custom render pipelines.
*/
public function testCustomPipeline() {
\Drupal::service('module_installer')->install(array('quickedit_test'));
$custom_render_url = 'quickedit/form/node/1/body/en/quickedit_test-custom-render-data';
$this->drupalLogin($this->editorUser);
// Request editing to render results with the custom render pipeline.
$post = array('nocssjs' => 'true') + $this->getAjaxPageStatePostData();
$response = $this->drupalPost($custom_render_url, '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$ajax_commands = Json::decode($response);
// Prepare form values for submission. drupalPostAJAX() is not suitable for
// handling pages with JSON responses, so we need our own solution here.
$form_tokens_found = preg_match('/\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match) && preg_match('/\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
$this->assertTrue($form_tokens_found, 'Form tokens found in output.');
if ($form_tokens_found) {
$post = array(
'form_id' => 'quickedit_field_form',
'form_token' => $token_match[1],
'form_build_id' => $build_id_match[1],
'body[0][summary]' => '',
'body[0][value]' => '<p>Fine thanks.</p>',
'body[0][format]' => 'filtered_html',
'op' => t('Save'),
);
// Assume there is another field on this page, which doesn't use a custom
// render pipeline, but the default one, and it uses the "full" view mode.
$post += array('other_view_modes[]' => 'full');
// Submit field form and check response. Should render with the custom
// render pipeline.
$response = $this->drupalPost($custom_render_url, '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(1, count($ajax_commands), 'The field form HTTP request results in one AJAX command.');
$this->assertIdentical('quickeditFieldFormSaved', $ajax_commands[0]['command'], 'The first AJAX command is a quickeditFieldFormSaved command.');
$this->assertTrue(strpos($ajax_commands[0]['data'], 'Fine thanks.'), 'Form value saved and printed back.');
$this->assertTrue(strpos($ajax_commands[0]['data'], '<div class="quickedit-test-wrapper">') !== FALSE, 'Custom render pipeline used to render the value.');
$this->assertIdentical(array_keys($ajax_commands[0]['other_view_modes']), array('full'), 'Field was also rendered in the "full" view mode.');
$this->assertTrue(strpos($ajax_commands[0]['other_view_modes']['full'], 'Fine thanks.'), '"full" version of field contains the form value.');
}
}
/**
* Tests Quick Edit on a node that was concurrently edited on the full node
* form.
*/
public function testConcurrentEdit() {
$this->drupalLogin($this->editorUser);
$post = array('nocssjs' => 'true') + $this->getAjaxPageStatePostData();
$response = $this->drupalPost('quickedit/form/' . 'node/1/body/en/full', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
// Prepare form values for submission. drupalPostAJAX() is not suitable for
// handling pages with JSON responses, so we need our own solution here.
$form_tokens_found = preg_match('/\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match) && preg_match('/\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
$this->assertTrue($form_tokens_found, 'Form tokens found in output.');
if ($form_tokens_found) {
$post = array(
'nocssjs' => 'true',
'form_id' => 'quickedit_field_form',
'form_token' => $token_match[1],
'form_build_id' => $build_id_match[1],
'body[0][summary]' => '',
'body[0][value]' => '<p>Fine thanks.</p>',
'body[0][format]' => 'filtered_html',
'op' => t('Save'),
);
// Save the node on the regular node edit form.
$this->drupalPostForm('node/1/edit', array(), t('Save'));
// Ensure different save timestamps for field editing.
sleep(2);
// Submit field form and check response. Should throw a validation error
// because the node was changed in the meantime.
$response = $this->drupalPost('quickedit/form/' . 'node/1/body/en/full', '', $post, ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical(2, count($ajax_commands), 'The field form HTTP request results in two AJAX commands.');
$this->assertIdentical('quickeditFieldFormValidationErrors', $ajax_commands[1]['command'], 'The second AJAX command is a quickeditFieldFormValidationErrors command.');
$this->assertTrue(strpos($ajax_commands[1]['data'], 'The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved.'), 'Error message returned to user.');
}
}
/**
* Tests that Quick Edit's data- attributes are present for content blocks.
*/
public function testContentBlock() {
\Drupal::service('module_installer')->install(array('block_content'));
// Create and place a content_block block.
$block = BlockContent::create([
'info' => $this->randomMachineName(),
'type' => 'basic',
'langcode' => 'en',
]);
$block->save();
$this->drupalPlaceBlock('block_content:' . $block->uuid());
// Check that the data- attribute is present.
$this->drupalLogin($this->editorUser);
$this->drupalGet('');
$this->assertRaw('data-quickedit-entity-id="block_content/1"');
}
/**
* Tests that Quick Edit can handle an image field.
*/
public function testImageField() {
// Add an image field to the content type.
FieldStorageConfig::create([
'field_name' => 'field_image',
'type' => 'image',
'entity_type' => 'node',
])->save();
FieldConfig::create([
'field_name' => 'field_image',
'field_type' => 'image',
'label' => t('Image'),
'entity_type' => 'node',
'bundle' => 'article',
])->save();
entity_get_form_display('node', 'article', 'default')
->setComponent('field_image', [
'type' => 'image_image',
])
->save();
// Add an image to the node.
$this->drupalLogin($this->editorUser);
$image = $this->drupalGetTestFiles('image')[0];
$this->drupalPostForm('node/1/edit', [
'files[field_image_0]' => $image->uri,
], t('Upload'));
$this->drupalPostForm(NULL, [
'field_image[0][alt]' => 'Vivamus aliquet elit',
], t('Save'));
// The image field form should load normally.
$response = $this->drupalPost('quickedit/form/node/1/field_image/en/full', '', ['nocssjs' => 'true'] + $this->getAjaxPageStatePostData(), ['query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax']]);
$this->assertResponse(200);
$ajax_commands = Json::decode($response);
$this->assertIdentical('<form ', Unicode::substr($ajax_commands[0]['data'], 0, 6), 'The quickeditFieldForm command contains a form.');
}
}