View source
<?php
namespace Drupal\views_entity_form_field\Plugin\views\field;
use Drupal\Component\Plugin\DependentPluginInterface;
use Drupal\Component\Plugin\Factory\DefaultFactory;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\WidgetPluginManager;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\PluginDependencyTrait;
use Drupal\views\Entity\Render\EntityTranslationRenderTrait;
use Drupal\views\Plugin\DependentWithRemovalPluginInterface;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\Plugin\views\field\UncacheableFieldHandlerTrait;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EntityFormField extends FieldPluginBase implements CacheableDependencyInterface, DependentWithRemovalPluginInterface {
use EntityTranslationRenderTrait;
use PluginDependencyTrait;
use UncacheableFieldHandlerTrait;
protected $entityFieldManager;
protected $entityTypeManager;
protected $entityTypeId;
protected $fieldTypeManager;
protected $fieldWidgetManager;
protected $fieldWidgets;
protected $languageManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityFieldManagerInterface $entity_field_manager, EntityTypeManagerInterface $entity_type_manager, WidgetPluginManager $field_widget_manager, LanguageManagerInterface $language_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityFieldManager = $entity_field_manager;
$this->entityTypeManager = $entity_type_manager;
$this->fieldWidgetManager = $field_widget_manager;
$this->languageManager = $language_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_field.manager'), $container
->get('entity_type.manager'), $container
->get('plugin.manager.field.widget'), $container
->get('language_manager'));
}
protected function getEntityTypeManager() {
return $this->entityTypeManager;
}
protected function getFieldTypeManager() {
if (is_null($this->fieldTypeManager)) {
$this->fieldTypeManager = \Drupal::service('plugin.manager.field.field_type');
}
return $this->fieldTypeManager;
}
protected function getEntityTypeId() {
if (is_null($this->entityTypeId)) {
$this->entityTypeId = $this
->getEntityType();
}
return $this->entityTypeId;
}
protected function getBundleFieldDefinition($bundle = NULL) {
$bundle = !is_null($bundle) ? $bundle : reset($this->definition['bundles']);
$field_definitions = $this->entityFieldManager
->getFieldDefinitions($this
->getEntityTypeId(), $bundle);
return array_key_exists($this->definition['field_name'], $field_definitions) ? $field_definitions[$this->definition['field_name']] : NULL;
}
protected function getPluginApplicableOptions(FieldDefinitionInterface $field_definition) {
$options = $this->fieldWidgetManager
->getOptions($field_definition
->getType());
$applicable_options = [];
foreach ($options as $option => $label) {
$plugin_class = DefaultFactory::getPluginClass($option, $this->fieldWidgetManager
->getDefinition($option));
if ($plugin_class::isApplicable($field_definition)) {
$applicable_options[$option] = $label;
}
}
return $applicable_options;
}
protected function getPluginDefaultOption($field_type) {
$definition = $this
->getFieldTypeManager()
->getDefinition($field_type, FALSE);
return $definition && isset($definition['default_widget']) ? $definition['default_widget'] : NULL;
}
protected function getPluginInstance($bundle = NULL) {
$bundle = !is_null($bundle) ? $bundle : reset($this->definition['bundles']);
if (!isset($this->fieldWidgets[$bundle]) && ($field_definition = $this
->getBundleFieldDefinition($bundle))) {
$options = [
'field_definition' => $field_definition,
'form_mode' => 'views_view',
'prepare' => FALSE,
'configuration' => $this->options['plugin'],
];
if (isset($options['configuration']['type']) && empty($options['configuration']['type'])) {
unset($options['configuration']['type']);
$options['prepare'] = TRUE;
}
$this->fieldWidgets[$bundle] = $this->fieldWidgetManager
->getInstance($options);
}
return $this->fieldWidgets[$bundle];
}
protected function getLanguageManager() {
return $this->languageManager;
}
protected function getView() {
return $this->view;
}
public function getCacheContexts() {
return Cache::mergeContexts($this
->getEntityTranslationRenderer()
->getCacheContexts(), [
'user',
]);
}
public function getCacheMaxAge() {
return Cache::PERMANENT;
}
public function getCacheTags() {
$field_definition = $this
->getBundleFieldDefinition();
$field_storage_definition = $field_definition
->getFieldStorageDefinition();
return Cache::mergeTags($field_definition instanceof CacheableDependencyInterface ? $field_definition
->getCacheTags() : [], $field_storage_definition instanceof CacheableDependencyInterface ? $field_storage_definition
->getCacheTags() : []);
}
public function calculateDependencies() {
$this->dependencies = parent::calculateDependencies();
if (($field_definition = $this
->getBundleFieldDefinition()) && $field_definition instanceof EntityInterface) {
$this->dependencies['config'][] = $field_definition
->getConfigDependencyName();
}
if (!empty($this->options['type'])) {
$this->dependencies['module'][] = $this->fieldWidgetManager
->getDefinition($this->options['type'])['provider'];
if (($formatter = $this
->getPluginInstance()) && $formatter instanceof DependentPluginInterface) {
$this
->calculatePluginDependencies($formatter);
}
}
return $this->dependencies;
}
public function onDependencyRemoval(array $dependencies) {
$remove = FALSE;
$current_dependencies = $this
->calculateDependencies();
foreach ($current_dependencies as $group => $dependency_list) {
foreach ($dependency_list as $config_key) {
if (isset($dependencies[$group]) && array_key_exists($config_key, $dependencies[$group])) {
$remove = TRUE;
break 2;
}
}
}
return $remove;
}
public function clickSortable() {
return FALSE;
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['plugin']['contains']['hide_title']['default'] = TRUE;
$options['plugin']['contains']['hide_description']['default'] = TRUE;
$options['plugin']['contains']['type']['default'] = [];
$options['plugin']['contains']['settings']['default'] = [];
$options['plugin']['contains']['third_party_settings']['default'] = [];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$field_definition = $this
->getBundleFieldDefinition();
$form['plugin'] = [
'type' => [
'#type' => 'select',
'#title' => $this
->t('Widget type'),
'#options' => $this
->getPluginApplicableOptions($field_definition),
'#default_value' => $this->options['plugin']['type'],
'#attributes' => [
'class' => [
'field-plugin-type',
],
],
'#ajax' => [
'url' => views_ui_build_form_url($form_state),
],
'#submit' => [
[
$this,
'submitTemporaryForm',
],
],
'#executes_submit_callback' => TRUE,
],
'hide_title' => [
'#type' => 'checkbox',
'#title' => $this
->t('Hide widget title'),
'#default_value' => $this->options['plugin']['hide_title'],
],
'hide_description' => [
'#type' => 'checkbox',
'#title' => $this
->t('Hide widget description'),
'#default_value' => $this->options['plugin']['hide_description'],
],
'settings_edit_form' => [],
];
if ($plugin = $this
->getPluginInstance()) {
$settings_form = $plugin
->settingsForm($form, $form_state);
$third_party_settings_form = [];
foreach ($this->moduleHandler
->getImplementations('field_widget_third_party_settings_form') as $module) {
$third_party_settings_form[$module] = $this->moduleHandler
->invoke($module, 'field_widget_third_party_settings_form', [
$plugin,
$field_definition,
'views_view',
$form,
$form_state,
]);
}
if ($settings_form || $third_party_settings_form) {
$form['plugin']['#cell_attributes'] = [
'colspan' => 3,
];
$form['plugin']['settings_edit_form'] = [
'#type' => 'fieldset',
'#title' => $this
->t('Widget settings'),
'#attributes' => [
'class' => [
'field-plugin-settings-edit-form',
],
],
'settings' => $settings_form,
'third_party_settings' => $third_party_settings_form,
];
$form['#attributes']['class'][] = 'field-plugin-settings-editing';
}
}
}
public function submitFormCalculateOptions(array $options, array $form_state_options) {
unset($options['settings']);
$options = $form_state_options + $options;
if (!isset($options['settings'])) {
$options['settings'] = [];
}
return $options;
}
public function submitOptionsForm(&$form, FormStateInterface $form_state) {
parent::submitOptionsForm($form, $form_state);
$options =& $form_state
->getValue('options');
$options['plugin']['settings'] = isset($options['plugin']['settings_edit_form']['settings']) ? array_intersect_key($options['plugin']['settings_edit_form']['settings'], $this->fieldWidgetManager
->getDefaultSettings($options['plugin']['type'])) : [];
$options['plugin']['third_party_settings'] = isset($options['plugin']['settings_edit_form']['third_party_settings']) ? $options['plugin']['settings_edit_form']['third_party_settings'] : [];
unset($options['plugin']['settings_edit_form']);
}
public function getValue(ResultRow $row, $field = NULL) {
return '<!--form-item-' . $this->options['id'] . '--' . $row->index . '-->';
}
public function viewsForm(array &$form, FormStateInterface $form_state) {
$field_name = $this->definition['field_name'];
$form['#cache']['max-age'] = 0;
$form['#attached']['library'][] = 'views_entity_form_field/views_form';
$form['#attributes']['class'][] = 'views-entity-form';
$form['#process'][] = [
$this,
'viewsFormProcess',
];
$form['#tree'] = TRUE;
$form += [
'#parents' => [],
];
if (!empty($this
->getView()->result)) {
$form[$this->options['id']]['#tree'] = TRUE;
$form[$this->options['id']]['#entity_form_field'] = TRUE;
foreach ($this
->getView()->result as $row_index => $row) {
$form[$this->options['id']][$row_index]['#parents'] = [
$this->options['id'],
$row_index,
];
$form[$this->options['id']][$row_index]['#tree'] = TRUE;
if ($this
->getEntity($row)) {
$entity = $this
->getEntityTranslation($this
->getEntity($row), $row);
if ($entity
->hasField($field_name) && $this
->getBundleFieldDefinition($entity
->bundle())
->isDisplayConfigurable('form')) {
$items = $entity
->get($field_name)
->filterEmptyItems();
$form[$this->options['id']][$row_index][$field_name] = $this
->getPluginInstance()
->form($items, $form[$this->options['id']][$row_index], $form_state);
$form[$this->options['id']][$row_index][$field_name]['#access'] = $entity
->access('update') && $items
->access('edit');
$form[$this->options['id']][$row_index][$field_name]['#cache']['contexts'] = $entity
->getCacheContexts();
$form[$this->options['id']][$row_index][$field_name]['#cache']['tags'] = $entity
->getCacheTags();
$form[$this->options['id']][$row_index][$field_name]['#parents'] = [
$this->options['id'],
$row_index,
$field_name,
];
if ($this->options['plugin']['hide_title']) {
$form[$this->options['id']][$row_index][$field_name]['#attributes']['class'][] = 'views-entity-form-field-field-label-hidden';
}
if ($this->options['plugin']['hide_description']) {
$form[$this->options['id']][$row_index][$field_name]['#attributes']['class'][] = 'views-entity-form-field-field-description-hidden';
}
}
}
}
}
}
public function viewsFormProcess(array $element, FormStateInterface $form_state) {
$element['#submit'][] = [
$this,
'saveEntities',
];
return $element;
}
public function viewsFormValidate(array &$form, FormStateInterface $form_state) {
$form_state
->cleanValues();
$this
->buildEntities($form, $form_state, TRUE);
}
public function viewsFormSubmit(array &$form, FormStateInterface $form_state) {
$form_state
->cleanValues();
$this
->buildEntities($form, $form_state);
}
protected function buildEntities(array &$form, FormStateInterface $form_state, $validate = FALSE) {
$field_name = $this->definition['field_name'];
foreach ($this
->getView()->result as $row_index => $row) {
$entity = $this
->getEntity($row);
if ($entity && $entity
->hasField($field_name) && $this
->getBundleFieldDefinition($entity
->bundle())
->isDisplayConfigurable('form')) {
$items = $entity
->get($field_name)
->filterEmptyItems();
$this
->getPluginInstance($entity
->bundle())
->extractFormValues($items, $form[$this->options['id']][$row_index], $form_state);
if ($validate) {
$violations = $items
->validate();
if ($violations
->count() > 0) {
$this
->getPluginInstance($entity
->bundle())
->flagErrors($items, $violations, $form[$this->options['id']][$row_index], $form_state);
}
}
}
}
}
public function saveEntities(array &$form, FormStateInterface $form_state) {
if (is_null($form_state
->getTemporaryValue([
'saved_relationships',
$this->relationship,
]))) {
$storage = $this
->getEntityTypeManager()
->getStorage($this
->getEntityTypeId());
$rows_saved = [];
$rows_failed = [];
foreach ($this
->getView()->result as $row_index => $row) {
$entity = $this
->getEntity($row);
if ($entity) {
$entity = $this
->getEntityTranslation($entity, $row);
$original_entity = $this
->getEntityTranslation($storage
->loadUnchanged($entity
->id()), $row);
try {
if ($this
->entityShouldBeSaved($entity, $original_entity)) {
$storage
->save($entity);
$rows_saved[$row_index] = $entity
->label();
}
} catch (\Exception $exception) {
$rows_failed[$row_index] = $entity
->label();
}
}
}
$messenger = \Drupal::messenger();
$entity_type_definition = $this->entityTypeManager
->getDefinition($this
->getEntityTypeId());
$messenger
->addStatus($this
->formatPlural(count($rows_saved), '@count @singular_label saved.', '@count @plural_label saved.', [
'@count' => count($rows_saved),
'@singular_label' => $entity_type_definition
->getSingularLabel(),
'@plural_label' => $entity_type_definition
->getPluralLabel(),
]));
if (count($rows_failed) > 0) {
$messenger
->addWarning($this
->formatPlural(count($rows_failed), '@count @singular_label failed to save: @labels', '@count @plural_label failed to save: @labels', [
'@count' => count($rows_failed),
'@singular_label' => $entity_type_definition
->getSingularLabel(),
'@plural_label' => $entity_type_definition
->getPluralLabel(),
'@labels' => implode(', ', $rows_failed),
]));
}
$form_state
->setTemporaryValue([
'saved_relationships',
$this->relationship,
], TRUE);
}
}
protected function entityShouldBeSaved(EntityInterface $entity, EntityInterface $original_entity) {
$save_entity = FALSE;
foreach ($entity as $field_name => $new_field) {
$original_field = $original_entity
->get($field_name);
if (!$new_field
->equals($original_field)) {
$save_entity = TRUE;
break;
}
}
return $save_entity;
}
public function query() {
}
}