View source
<?php
namespace Drupal\paragraphs\Plugin\Field\FieldWidget;
use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldFilteredMarkup;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\SubformState;
use Drupal\Core\Render\Element;
use Drupal\Core\TypedData\TranslationStatusInterface;
use Drupal\field_group\FormatterHelper;
use Drupal\paragraphs\ParagraphInterface;
use Drupal\paragraphs\Plugin\EntityReferenceSelection\ParagraphSelection;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\ConstraintViolationListInterface;
class ParagraphsWidget extends WidgetBase {
const ACTION_POSITION_BASE = 1;
const ACTION_POSITION_HEADER = 2;
const ACTION_POSITION_ACTIONS = 3;
protected $isTranslating;
protected $fieldIdPrefix;
protected $fieldWrapperId;
protected $realItemCount;
protected $fieldParents;
protected $accessOptions = NULL;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings) {
if (isset($settings['edit_mode']) && $settings['edit_mode'] === 'preview') {
$settings['edit_mode'] = 'closed';
$settings['closed_mode'] = 'preview';
}
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
}
public static function defaultSettings() {
return array(
'title' => t('Paragraph'),
'title_plural' => t('Paragraphs'),
'edit_mode' => 'open',
'closed_mode' => 'summary',
'autocollapse' => 'none',
'closed_mode_threshold' => 0,
'add_mode' => 'dropdown',
'form_display_mode' => 'default',
'default_paragraph_type' => '',
'features' => [
'duplicate' => 'duplicate',
'collapse_edit_all' => 'collapse_edit_all',
],
);
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = array();
$elements['title'] = array(
'#type' => 'textfield',
'#title' => $this
->t('Paragraph Title'),
'#description' => $this
->t('Label to appear as title on the button as "Add new [title]", this label is translatable'),
'#default_value' => $this
->getSetting('title'),
'#required' => TRUE,
);
$elements['title_plural'] = array(
'#type' => 'textfield',
'#title' => $this
->t('Plural Paragraph Title'),
'#description' => $this
->t('Title in its plural form.'),
'#default_value' => $this
->getSetting('title_plural'),
'#required' => TRUE,
);
$elements['edit_mode'] = array(
'#type' => 'select',
'#title' => $this
->t('Edit mode'),
'#description' => $this
->t('The mode the paragraph is in by default.'),
'#options' => $this
->getSettingOptions('edit_mode'),
'#default_value' => $this
->getSetting('edit_mode'),
'#required' => TRUE,
);
$elements['closed_mode'] = [
'#type' => 'select',
'#title' => $this
->t('Closed mode'),
'#description' => $this
->t('How to display the paragraphs, when the widget is closed. Preview will render the paragraph in the preview view mode and typically needs a custom admin theme.'),
'#options' => $this
->getSettingOptions('closed_mode'),
'#default_value' => $this
->getSetting('closed_mode'),
'#required' => TRUE,
];
$elements['autocollapse'] = [
'#type' => 'select',
'#title' => $this
->t('Autocollapse'),
'#description' => $this
->t('When a paragraph is opened for editing, close others.'),
'#options' => $this
->getSettingOptions('autocollapse'),
'#default_value' => $this
->getSetting('autocollapse'),
'#required' => TRUE,
'#states' => [
'visible' => [
'select[name="fields[' . $this->fieldDefinition
->getName() . '][settings_edit_form][settings][edit_mode]"]' => [
'value' => 'closed',
],
],
],
];
$elements['closed_mode_threshold'] = [
'#type' => 'number',
'#title' => $this
->t('Closed mode threshold'),
'#default_value' => $this
->getSetting('closed_mode_threshold'),
'#description' => $this
->t('Number of items considered to leave paragraphs open e.g the threshold is 3, if a paragraph has less than 3 items, leave it open.'),
'#min' => 0,
'#states' => [
'invisible' => [
'select[name="fields[' . $this->fieldDefinition
->getName() . '][settings_edit_form][settings][edit_mode]"]' => [
'value' => 'open',
],
],
],
];
$elements['add_mode'] = array(
'#type' => 'select',
'#title' => $this
->t('Add mode'),
'#description' => $this
->t('The way to add new Paragraphs.'),
'#options' => $this
->getSettingOptions('add_mode'),
'#default_value' => $this
->getSetting('add_mode'),
'#required' => TRUE,
);
$elements['form_display_mode'] = array(
'#type' => 'select',
'#options' => \Drupal::service('entity_display.repository')
->getFormModeOptions($this
->getFieldSetting('target_type')),
'#description' => $this
->t('The form display mode to use when rendering the paragraph form.'),
'#title' => $this
->t('Form display mode'),
'#default_value' => $this
->getSetting('form_display_mode'),
'#required' => TRUE,
);
$options = [];
foreach ($this
->getAllowedTypes() as $key => $bundle) {
$options[$key] = $bundle['label'];
}
$elements['default_paragraph_type'] = [
'#type' => 'select',
'#title' => $this
->t('Default paragraph type'),
'#empty_value' => '_none',
'#default_value' => $this
->getDefaultParagraphTypeMachineName(),
'#options' => $options,
'#description' => $this
->t('When creating a new host entity, a paragraph of this type is added.'),
];
$elements['features'] = [
'#type' => 'checkboxes',
'#title' => $this
->t('Enable widget features'),
'#options' => $this
->getSettingOptions('features'),
'#default_value' => $this
->getSetting('features'),
'#description' => $this
->t('When editing, available as action. "Add above" only works in add mode "Modal form"'),
'#multiple' => TRUE,
];
return $elements;
}
protected function getSettingOptions($setting_name) {
switch ($setting_name) {
case 'edit_mode':
$options = [
'open' => $this
->t('Open'),
'closed' => $this
->t('Closed'),
'closed_expand_nested' => $this
->t('Closed, show nested'),
];
break;
case 'closed_mode':
$options = [
'summary' => $this
->t('Summary'),
'preview' => $this
->t('Preview'),
];
break;
case 'autocollapse':
$options = [
'none' => $this
->t('None'),
'all' => $this
->t('All'),
];
break;
case 'add_mode':
$options = [
'select' => $this
->t('Select list'),
'button' => $this
->t('Buttons'),
'dropdown' => $this
->t('Dropdown button'),
'modal' => $this
->t('Modal form'),
];
break;
case 'features':
$options = [
'duplicate' => $this
->t('Duplicate'),
'collapse_edit_all' => $this
->t('Collapse / Edit all'),
'add_above' => $this
->t('Add above'),
];
break;
}
return isset($options) ? $options : NULL;
}
public function settingsSummary() {
$summary = array();
$summary[] = $this
->t('Title: @title', [
'@title' => $this
->getSetting('title'),
]);
$summary[] = $this
->t('Plural title: @title_plural', [
'@title_plural' => $this
->getSetting('title_plural'),
]);
$edit_mode = $this
->getSettingOptions('edit_mode')[$this
->getSetting('edit_mode')];
$closed_mode = $this
->getSettingOptions('closed_mode')[$this
->getSetting('closed_mode')];
$add_mode = $this
->getSettingOptions('add_mode')[$this
->getSetting('add_mode')];
$summary[] = $this
->t('Edit mode: @edit_mode', [
'@edit_mode' => $edit_mode,
]);
$summary[] = $this
->t('Closed mode: @closed_mode', [
'@closed_mode' => $closed_mode,
]);
if ($this
->getSetting('edit_mode') == 'closed') {
$autocollapse = $this
->getSettingOptions('autocollapse')[$this
->getSetting('autocollapse')];
$summary[] = $this
->t('Autocollapse: @autocollapse', [
'@autocollapse' => $autocollapse,
]);
}
if (($this
->getSetting('edit_mode') == 'closed' || $this
->getSetting('edit_mode') == 'closed_expand_nested') && $this
->getSetting('closed_mode_threshold') > 0) {
$summary[] = $this
->t('Closed mode threshold: @mode_limit', [
'@mode_limit' => $this
->getSetting('closed_mode_threshold'),
]);
}
$summary[] = $this
->t('Add mode: @add_mode', [
'@add_mode' => $add_mode,
]);
$summary[] = $this
->t('Form display mode: @form_display_mode', [
'@form_display_mode' => $this
->getSetting('form_display_mode'),
]);
if ($this
->getDefaultParagraphTypeLabelName() !== NULL) {
$summary[] = $this
->t('Default paragraph type: @default_paragraph_type', [
'@default_paragraph_type' => $this
->getDefaultParagraphTypeLabelName(),
]);
}
$features_labels = array_intersect_key($this
->getSettingOptions('features'), array_filter($this
->getSetting('features')));
if (!empty($features_labels)) {
$summary[] = $this
->t('Features: @features', [
'@features' => implode(', ', $features_labels),
]);
}
return $summary;
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$field_name = $this->fieldDefinition
->getName();
$parents = $element['#field_parents'];
$paragraphs_entity = NULL;
$host = $items
->getEntity();
$widget_state = static::getWidgetState($parents, $field_name, $form_state);
$entity_type_manager = \Drupal::entityTypeManager();
$target_type = $this
->getFieldSetting('target_type');
$item_mode = isset($widget_state['paragraphs'][$delta]['mode']) ? $widget_state['paragraphs'][$delta]['mode'] : 'edit';
$default_edit_mode = $this
->getSetting('edit_mode');
$closed_mode_setting = isset($widget_state['closed_mode']) ? $widget_state['closed_mode'] : $this
->getSetting('closed_mode');
$autocollapse_setting = isset($widget_state['autocollapse']) ? $widget_state['autocollapse'] : $this
->getSetting('autocollapse');
$show_must_be_saved_warning = !empty($widget_state['paragraphs'][$delta]['show_warning']);
if (isset($widget_state['paragraphs'][$delta]['entity'])) {
$paragraphs_entity = $widget_state['paragraphs'][$delta]['entity'];
}
elseif (isset($items[$delta]->entity)) {
$paragraphs_entity = $items[$delta]->entity;
if (!isset($widget_state['paragraphs'][$delta]['mode'])) {
if ($default_edit_mode == 'open' || $widget_state['items_count'] < $this
->getSetting('closed_mode_threshold')) {
$item_mode = 'edit';
}
elseif ($default_edit_mode == 'closed') {
$item_mode = 'closed';
}
elseif ($default_edit_mode == 'closed_expand_nested') {
$item_mode = 'closed';
$field_definitions = $paragraphs_entity
->getFieldDefinitions();
foreach ($field_definitions as $field_definition) {
if ($field_definition
->getType() == 'entity_reference_revisions' && $field_definition
->getSetting('target_type') == 'paragraph') {
$item_mode = 'edit';
break;
}
}
}
}
}
elseif (isset($widget_state['selected_bundle'])) {
$entity_type = $entity_type_manager
->getDefinition($target_type);
$bundle_key = $entity_type
->getKey('bundle');
$paragraphs_entity = $entity_type_manager
->getStorage($target_type)
->create(array(
$bundle_key => $widget_state['selected_bundle'],
));
$paragraphs_entity
->setParentEntity($host, $field_name);
$item_mode = 'edit';
}
if ($paragraphs_entity) {
$this
->initIsTranslating($form_state, $host);
$langcode = $form_state
->get('langcode');
if (!$this->isTranslating) {
$langcode_key = $paragraphs_entity
->getEntityType()
->getKey('langcode');
if ($paragraphs_entity
->get($langcode_key)->value != $langcode) {
if ($paragraphs_entity
->hasTranslation($langcode)) {
$paragraphs_entity = $paragraphs_entity
->getTranslation($langcode);
}
else {
$paragraphs_entity
->set($langcode_key, $langcode);
}
}
}
else {
if (!$form_state
->isRebuilding() && $host
->getTranslationStatus($langcode) == TranslationStatusInterface::TRANSLATION_CREATED) {
$item_mode = 'edit';
}
if (!$paragraphs_entity
->hasTranslation($langcode)) {
$entity_langcode = $paragraphs_entity
->language()
->getId();
$source = $form_state
->get([
'content_translation',
'source',
]);
$source_langcode = $source ? $source
->getId() : $entity_langcode;
if ($paragraphs_entity
->hasTranslation($source_langcode)) {
$paragraphs_entity = $paragraphs_entity
->getTranslation($source_langcode);
}
if ($paragraphs_entity
->hasField('content_translation_source')) {
$paragraphs_entity
->addTranslation($langcode, $paragraphs_entity
->toArray());
$translation = $paragraphs_entity
->getTranslation($langcode);
$manager = \Drupal::service('content_translation.manager');
$manager
->getTranslationMetadata($translation)
->setSource($paragraphs_entity
->language()
->getId());
}
}
if ($paragraphs_entity
->hasField('content_translation_source')) {
$paragraphs_entity = $paragraphs_entity
->getTranslation($langcode);
}
}
$translating_force_close = FALSE;
if (\Drupal::moduleHandler()
->moduleExists('content_translation')) {
$manager = \Drupal::service('content_translation.manager');
$settings = $manager
->getBundleTranslationSettings('paragraph', $paragraphs_entity
->getParagraphType()
->id());
if (!empty($settings['untranslatable_fields_hide']) && $this->isTranslating) {
$translating_force_close = TRUE;
$display = EntityFormDisplay::collectRenderDisplay($paragraphs_entity, $this
->getSetting('form_display_mode'));
foreach (array_keys($display
->get('content')) as $field) {
if ($paragraphs_entity
->hasField($field)) {
$field_definition = $paragraphs_entity
->get($field)
->getFieldDefinition();
$is_paragraph = $field_definition
->getType() == 'entity_reference_revisions' && $field_definition
->getSetting('target_type') == 'paragraph';
if ($is_paragraph || $field_definition
->isTranslatable()) {
$translating_force_close = FALSE;
break;
}
}
}
if ($translating_force_close) {
$item_mode = 'closed';
}
}
}
$element_parents = $parents;
$element_parents[] = $field_name;
$element_parents[] = $delta;
$element_parents[] = 'subform';
$id_prefix = implode('-', array_merge($parents, array(
$field_name,
$delta,
)));
$wrapper_id = Html::getUniqueId($id_prefix . '-item-wrapper');
$element += array(
'#type' => 'container',
'#element_validate' => array(
array(
$this,
'elementValidate',
),
),
'#paragraph_type' => $paragraphs_entity
->bundle(),
'subform' => array(
'#type' => 'container',
'#parents' => $element_parents,
),
);
$element['#prefix'] = '<div id="' . $wrapper_id . '">';
$element['#suffix'] = '</div>';
$element['top'] = [
'#type' => 'container',
'#weight' => -1000,
'#attributes' => [
'class' => [
'paragraph-top',
$this
->isFeatureEnabled('add_above') ? 'add-above-on' : 'add-above-off',
],
],
'type' => [
'#type' => 'container',
'#attributes' => [
'class' => [
'paragraph-type',
],
],
],
'icons' => [
'#type' => 'container',
'#attributes' => [
'class' => [
'paragraph-info',
],
],
],
'summary' => [
'#type' => 'container',
'#attributes' => [
'class' => [
'paragraph-summary',
],
],
],
'actions' => [
'#type' => 'paragraphs_actions',
],
];
$info = [];
$item_bundles = \Drupal::service('entity_type.bundle.info')
->getBundleInfo($target_type);
if (isset($item_bundles[$paragraphs_entity
->bundle()])) {
$bundle_info = $item_bundles[$paragraphs_entity
->bundle()];
$element['top']['type']['label'] = [
'#markup' => $bundle_info['label'],
];
if ($icon_url = $paragraphs_entity
->getParagraphType()
->getIconUrl()) {
$element['top']['type']['icon'] = [
'#theme' => 'image',
'#uri' => $icon_url,
'#attributes' => [
'class' => [
'paragraph-type-icon',
],
'title' => $bundle_info['label'],
],
'#weight' => 0,
'#height' => 16,
'#width' => 16,
];
}
$element['top']['type']['label'] = [
'#markup' => '<span class="paragraph-type-label">' . $bundle_info['label'] . '</span>',
'#weight' => 1,
];
$widget_actions = [
'actions' => [],
'dropdown_actions' => [],
];
$widget_actions['dropdown_actions']['duplicate_button'] = [
'#type' => 'submit',
'#value' => $this
->t('Duplicate'),
'#name' => $id_prefix . '_duplicate',
'#weight' => 502,
'#submit' => [
[
get_class($this),
'duplicateSubmit',
],
],
'#limit_validation_errors' => [
array_merge($parents, [
$field_name,
$delta,
]),
],
'#delta' => $delta,
'#ajax' => [
'callback' => [
get_class($this),
'itemAjax',
],
'wrapper' => $widget_state['ajax_wrapper_id'],
],
'#access' => $this
->duplicateButtonAccess($paragraphs_entity),
'#attributes' => [
'class' => [
'button--small',
],
],
];
if (!$paragraphs_entity
->access('update')) {
$item_mode = 'closed';
}
if ($item_mode != 'remove') {
$widget_actions['dropdown_actions']['remove_button'] = [
'#type' => 'submit',
'#value' => $this
->t('Remove'),
'#name' => $id_prefix . '_remove',
'#weight' => 501,
'#submit' => [
[
get_class($this),
'paragraphsItemSubmit',
],
],
'#limit_validation_errors' => [],
'#delta' => $delta,
'#ajax' => [
'callback' => array(
get_class($this),
'itemAjax',
),
'wrapper' => $widget_state['ajax_wrapper_id'],
],
'#access' => $this
->removeButtonAccess($paragraphs_entity),
'#paragraphs_mode' => 'remove',
'#attributes' => [
'class' => [
'button--small',
],
],
];
}
if ($item_mode == 'edit') {
if (isset($paragraphs_entity)) {
$widget_actions['actions']['collapse_button'] = [
'#value' => $this
->t('Collapse'),
'#name' => $id_prefix . '_collapse',
'#weight' => 1,
'#submit' => [
[
get_class($this),
'paragraphsItemSubmit',
],
],
'#limit_validation_errors' => [
array_merge($parents, [
$field_name,
$delta,
]),
],
'#delta' => $delta,
'#ajax' => [
'callback' => [
get_class($this),
'itemAjax',
],
'wrapper' => $widget_state['ajax_wrapper_id'],
],
'#access' => $paragraphs_entity
->access('update') && !$translating_force_close,
'#paragraphs_mode' => 'closed',
'#paragraphs_show_warning' => TRUE,
'#attributes' => [
'class' => [
'paragraphs-icon-button',
'paragraphs-icon-button-collapse',
'button--extrasmall',
],
'title' => $this
->t('Collapse'),
],
];
}
}
else {
$widget_actions['actions']['edit_button'] = $this
->expandButton([
'#type' => 'submit',
'#value' => $this
->t('Edit'),
'#name' => $id_prefix . '_edit',
'#weight' => 1,
'#submit' => [
[
get_class($this),
'paragraphsItemSubmit',
],
],
'#limit_validation_errors' => [
array_merge($parents, [
$field_name,
$delta,
]),
],
'#delta' => $delta,
'#ajax' => [
'callback' => [
get_class($this),
'itemAjax',
],
'wrapper' => $widget_state['ajax_wrapper_id'],
],
'#access' => $paragraphs_entity
->access('update') && !$translating_force_close,
'#paragraphs_mode' => 'edit',
'#attributes' => [
'class' => [
'paragraphs-icon-button',
'paragraphs-icon-button-edit',
'button--extrasmall',
],
'title' => $this
->t('Edit'),
],
]);
if ($show_must_be_saved_warning && $paragraphs_entity
->isChanged()) {
$info['changed'] = [
'#theme' => 'paragraphs_info_icon',
'#message' => $this
->t('You have unsaved changes on this @title item.', [
'@title' => $this
->getSetting('title'),
]),
'#icon' => 'changed',
];
}
if (!$paragraphs_entity
->isPublished()) {
$info['preview'] = [
'#theme' => 'paragraphs_info_icon',
'#message' => $this
->t('Unpublished'),
'#icon' => 'view',
];
}
}
if (!$paragraphs_entity
->access('update')) {
$widget_actions['actions']['edit_disabled'] = [
'#theme' => 'paragraphs_info_icon',
'#message' => $this
->t('You are not allowed to edit or remove this @title.', [
'@title' => $this
->getSetting('title'),
]),
'#icon' => 'lock',
'#weight' => 1,
];
}
$delete_access = $paragraphs_entity
->isNew() || $paragraphs_entity
->access('delete');
if (!$paragraphs_entity
->access('update') && $delete_access) {
$info['edit'] = [
'#theme' => 'paragraphs_info_icon',
'#message' => $this
->t('You are not allowed to edit this @title.', [
'@title' => $this
->getSetting('title'),
]),
'#icon' => 'edit-disabled',
];
}
elseif (!$delete_access && $paragraphs_entity
->access('update')) {
$info['remove'] = [
'#theme' => 'paragraphs_info_icon',
'#message' => $this
->t('You are not allowed to remove this @title.', [
'@title' => $this
->getSetting('title'),
]),
'#icon' => 'delete-disabled',
];
}
$context = [
'form' => $form,
'widget' => self::getWidgetState($parents, $field_name, $form_state),
'items' => $items,
'delta' => $delta,
'element' => $element,
'form_state' => $form_state,
'paragraphs_entity' => $paragraphs_entity,
'is_translating' => $this->isTranslating,
'allow_reference_changes' => $this
->allowReferenceChanges(),
];
\Drupal::moduleHandler()
->alter('paragraphs_widget_actions', $widget_actions, $context);
if (!empty($widget_actions['actions'])) {
$element['top']['actions']['actions'] = array_map([
$this,
'expandButton',
], $widget_actions['actions']);
}
if (!empty($widget_actions['dropdown_actions'])) {
$element['top']['actions']['dropdown_actions'] = array_map([
$this,
'expandButton',
], $widget_actions['dropdown_actions']);
}
}
$display = EntityFormDisplay::collectRenderDisplay($paragraphs_entity, $this
->getSetting('form_display_mode'));
if (\Drupal::moduleHandler()
->moduleExists('field_group')) {
$context = [
'entity_type' => $paragraphs_entity
->getEntityTypeId(),
'bundle' => $paragraphs_entity
->bundle(),
'entity' => $paragraphs_entity,
'context' => 'form',
'display_context' => 'form',
'mode' => $display
->getMode(),
];
field_group_attach_groups($element['subform'], $context);
if (method_exists(FormatterHelper::class, 'formProcess')) {
$element['subform']['#process'][] = [
FormatterHelper::class,
'formProcess',
];
}
elseif (function_exists('field_group_form_pre_render')) {
$element['subform']['#pre_render'][] = 'field_group_form_pre_render';
}
elseif (function_exists('field_group_form_process')) {
$element['subform']['#process'][] = 'field_group_form_process';
}
}
if ($item_mode == 'edit') {
$display
->buildForm($paragraphs_entity, $element['subform'], $form_state);
$hide_untranslatable_fields = $paragraphs_entity
->isDefaultTranslationAffectedOnly();
$summary = $paragraphs_entity
->getSummaryItems();
if (!empty($summary)) {
$element['top']['summary']['fields_info'] = [
'#theme' => 'paragraphs_summary',
'#summary' => $summary,
'#expanded' => TRUE,
'#access' => $paragraphs_entity
->access('update') || $paragraphs_entity
->access('view'),
];
}
$info = array_merge($info, $paragraphs_entity
->getIcons());
foreach (Element::children($element['subform']) as $field) {
if ($paragraphs_entity
->hasField($field)) {
$field_definition = $paragraphs_entity
->get($field)
->getFieldDefinition();
$is_paragraph_field = FALSE;
if ($field_definition
->getType() == 'entity_reference_revisions') {
if ($field_definition
->getSetting('target_type') == 'paragraph') {
$is_paragraph_field = TRUE;
}
}
if (!$is_paragraph_field) {
$element['subform'][$field]['#attributes']['class'][] = 'paragraphs-content';
$element['top']['summary']['fields_info'] = [
'#theme' => 'paragraphs_summary',
'#summary' => $summary,
'#expanded' => TRUE,
'#access' => $paragraphs_entity
->access('update') || $paragraphs_entity
->access('view'),
];
}
$translatable = $field_definition
->isTranslatable();
if (!$translatable && $this->isTranslating && !$is_paragraph_field) {
if ($hide_untranslatable_fields) {
$element['subform'][$field]['#access'] = FALSE;
}
else {
$element['subform'][$field]['widget']['#after_build'][] = [
static::class,
'addTranslatabilityClue',
];
}
}
}
}
$paragraphs_type = $paragraphs_entity
->getParagraphType();
if ($paragraphs_type && \Drupal::currentUser()
->hasPermission('edit behavior plugin settings') && (!$this->isTranslating || !$hide_untranslatable_fields)) {
$element['behavior_plugins']['#weight'] = -99;
foreach ($paragraphs_type
->getEnabledBehaviorPlugins() as $plugin_id => $plugin) {
$element['behavior_plugins'][$plugin_id] = [
'#type' => 'container',
'#group' => implode('][', array_merge($element_parents, [
'paragraph_behavior',
])),
'#parents' => array_merge(array_slice($element_parents, 0, -1), [
'behavior_plugins',
$plugin_id,
]),
];
$subform_state = SubformState::createForSubform($element['behavior_plugins'][$plugin_id], $form, $form_state);
if ($plugin_form = $plugin
->buildBehaviorForm($paragraphs_entity, $element['behavior_plugins'][$plugin_id], $subform_state)) {
$element['behavior_plugins'][$plugin_id] = $plugin_form;
$element['behavior_plugins'][$plugin_id]['#attributes']['class'][] = 'paragraphs-behavior';
}
}
}
}
elseif ($item_mode == 'closed') {
$element['subform'] = [];
$element['behavior_plugins'] = [];
if ($closed_mode_setting === 'preview') {
$view_builder = $entity_type_manager
->getViewBuilder('paragraph');
$element['preview'] = $view_builder
->view($paragraphs_entity, 'preview', $paragraphs_entity
->language()
->getId());
$element['preview']['#access'] = $paragraphs_entity
->access('view');
}
else {
if ($paragraphs_entity) {
$summary = $paragraphs_entity
->getSummaryItems();
if (!empty($summary)) {
$element['top']['summary']['fields_info'] = [
'#theme' => 'paragraphs_summary',
'#summary' => $summary,
'#expanded' => FALSE,
'#access' => $paragraphs_entity
->access('update') || $paragraphs_entity
->access('view'),
];
}
$info = array_merge($info, $paragraphs_entity
->getIcons());
}
}
}
else {
$element['subform'] = array();
}
if (!empty($info)) {
foreach ($info as $info_item) {
if (!isset($info_item['#access']) || $info_item['#access']) {
$element['top']['icons']['items'] = $info;
break;
}
}
}
$element['subform']['#attributes']['class'][] = 'paragraphs-subform';
$element['subform']['#access'] = $paragraphs_entity
->access('update');
if ($item_mode == 'remove') {
$element['#access'] = FALSE;
}
$widget_state['paragraphs'][$delta]['entity'] = $paragraphs_entity;
$widget_state['paragraphs'][$delta]['display'] = $display;
$widget_state['paragraphs'][$delta]['mode'] = $item_mode;
$widget_state['closed_mode'] = $closed_mode_setting;
$widget_state['autocollapse'] = $autocollapse_setting;
$widget_state['autocollapse_default'] = $this
->getSetting('autocollapse');
static::setWidgetState($parents, $field_name, $form_state, $widget_state);
}
else {
$element['#access'] = FALSE;
}
return $element;
}
protected function buildModalAddForm(array &$element) {
$element['#theme'] = 'paragraphs_add_dialog';
$element['add_modal_form_area'] = [
'#type' => 'container',
'#attributes' => [
'class' => [
'paragraph-type-add-modal',
'first-button',
],
],
'#access' => $this
->allowReferenceChanges(),
'#weight' => -2000,
];
$element['add_modal_form_area']['add_more'] = [
'#type' => 'submit',
'#value' => $this
->t('Add @title', [
'@title' => $this
->getSetting('title'),
]),
'#name' => 'button_add_modal',
'#attributes' => [
'class' => [
'paragraph-type-add-modal-button',
'js-show',
'button--small',
],
],
];
$element['#attached']['library'][] = 'paragraphs/drupal.paragraphs.modal';
if ($this
->isFeatureEnabled('add_above')) {
$element['#attached']['library'][] = 'paragraphs/drupal.paragraphs.add_above_button';
}
}
public function getAllowedTypes(FieldDefinitionInterface $field_definition = NULL) {
$return_bundles = array();
$selection_manager = \Drupal::service('plugin.manager.entity_reference_selection');
$handler = $selection_manager
->getSelectionHandler($field_definition ?: $this->fieldDefinition);
if ($handler instanceof ParagraphSelection) {
$return_bundles = $handler
->getSortedAllowedTypes();
}
else {
$bundles = \Drupal::service('entity_type.bundle.info')
->getBundleInfo($field_definition ? $field_definition
->getSetting('target_type') : $this->fieldDefinition
->getSetting('target_type'));
$weight = 0;
foreach ($bundles as $machine_name => $bundle) {
if (empty($this
->getSelectionHandlerSetting('target_bundles')) || in_array($machine_name, $this
->getSelectionHandlerSetting('target_bundles'))) {
$return_bundles[$machine_name] = array(
'label' => $bundle['label'],
'weight' => $weight,
);
$weight++;
}
}
}
return $return_bundles;
}
public function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
$field_name = $this->fieldDefinition
->getName();
$cardinality = $this->fieldDefinition
->getFieldStorageDefinition()
->getCardinality();
$this->fieldParents = $form['#parents'];
$field_state = static::getWidgetState($this->fieldParents, $field_name, $form_state);
$max = $field_state['items_count'];
$entity_type_manager = \Drupal::entityTypeManager();
if ($max == 0 && $items
->getEntity()
->isNew()) {
$default_type = $this
->getDefaultParagraphTypeMachineName();
if ($default_type) {
$target_type = $this
->getFieldSetting('target_type');
$paragraphs_entity = $entity_type_manager
->getStorage($target_type)
->create([
'type' => $default_type,
]);
$paragraphs_entity
->setParentEntity($items
->getEntity(), $field_name);
$field_state['selected_bundle'] = $default_type;
$display = EntityFormDisplay::collectRenderDisplay($paragraphs_entity, $this
->getSetting('form_display_mode'));
$field_state['paragraphs'][0] = [
'entity' => $paragraphs_entity,
'display' => $display,
'mode' => 'edit',
'original_delta' => 1,
];
$max = 1;
$field_state['items_count'] = $max;
}
}
$this->realItemCount = $max;
$is_multiple = $this->fieldDefinition
->getFieldStorageDefinition()
->isMultiple();
$field_title = $this->fieldDefinition
->getLabel();
$description = FieldFilteredMarkup::create(\Drupal::token()
->replace($this->fieldDefinition
->getDescription()));
$elements = array();
$tabs = '';
$this->fieldIdPrefix = implode('-', array_merge($this->fieldParents, array(
$field_name,
)));
$this->fieldWrapperId = Html::getId($this->fieldIdPrefix . '-add-more-wrapper');
$field_prefix = strtr($this->fieldIdPrefix, '_', '-');
if (count($this->fieldParents) == 0) {
if ($items
->getEntity()
->getEntityTypeId() != 'paragraph') {
$tabs = '<ul class="paragraphs-tabs tabs primary clearfix"><li class="tabs__tab paragraphs_content_tab"><a href="#' . $field_prefix . '-values">' . $this
->t('Content', [], [
'context' => 'paragraphs',
]) . '</a></li><li class="tabs__tab paragraphs_behavior_tab"><a href="#' . $field_prefix . '-values">' . $this
->t('Behavior', [], [
'context' => 'paragraphs',
]) . '</a></li></ul>';
}
}
if (count($this->fieldParents) > 0) {
if ($items
->getEntity()
->getEntityTypeId() === 'paragraph') {
$form['#attributes']['class'][] = 'paragraphs-nested';
}
}
$elements['#prefix'] = '<div class="is-horizontal paragraphs-tabs-wrapper" id="' . $this->fieldWrapperId . '">' . $tabs;
$elements['#suffix'] = '</div>';
$field_state['ajax_wrapper_id'] = $this->fieldWrapperId;
static::setWidgetState($this->fieldParents, $field_name, $form_state, $field_state);
if (!empty($field_state['dragdrop'])) {
$elements['header_actions']['actions']['complete_button'] = $this
->expandButton([
'#type' => 'submit',
'#name' => $this->fieldIdPrefix . '_dragdrop_mode',
'#value' => $this
->t('Complete drag & drop'),
'#attributes' => [
'class' => [
'field-dragdrop-mode-submit',
],
],
'#submit' => [
[
get_class($this),
'dragDropModeSubmit',
],
],
'#ajax' => [
'callback' => [
get_class($this),
'dragDropModeAjax',
],
'wrapper' => $this->fieldWrapperId,
],
'#limit_validation_errors' => [
array_merge($this->fieldParents, [
$field_name,
]),
],
'#button_type' => 'primary',
]);
$elements['#attached']['library'][] = 'paragraphs/paragraphs-dragdrop';
$elements['dragdrop'] = $this
->buildNestedParagraphsFoDragDrop($form_state, NULL, []);
return $elements;
}
if ($max > 0) {
for ($delta = 0; $delta < $max; $delta++) {
if (!isset($items[$delta])) {
$items
->appendItem();
}
$element = array(
'#title' => $is_multiple ? '' : $field_title,
'#description' => $is_multiple ? '' : $description,
);
$element = $this
->formSingleElement($items, $delta, $element, $form, $form_state);
if ($element) {
if ($is_multiple) {
$element['_weight'] = array(
'#type' => 'weight',
'#title' => $this
->t('Weight for row @number', array(
'@number' => $delta + 1,
)),
'#title_display' => 'invisible',
'#delta' => $max,
'#default_value' => $items[$delta]->_weight ?: $delta,
'#weight' => 100,
);
}
if (isset($element['#access']) && !$element['#access']) {
$this->realItemCount--;
}
else {
$elements[$delta] = $element;
}
}
}
}
$field_state = static::getWidgetState($this->fieldParents, $field_name, $form_state);
$field_state['real_item_count'] = $this->realItemCount;
$field_state['add_mode'] = $this
->getSetting('add_mode');
static::setWidgetState($this->fieldParents, $field_name, $form_state, $field_state);
$elements += [
'#element_validate' => [
[
$this,
'multipleElementValidate',
],
],
'#required' => $this->fieldDefinition
->isRequired(),
'#field_name' => $field_name,
'#cardinality' => $cardinality,
'#max_delta' => $max - 1,
];
$elements += [
'#theme' => 'field_multiple_value_form',
'#field_name' => $field_name,
'#cardinality' => $cardinality,
'#cardinality_multiple' => TRUE,
'#required' => $this->fieldDefinition
->isRequired(),
'#title' => $field_title,
'#description' => $description,
'#max_delta' => $max - 1,
];
$host = $items
->getEntity();
$this
->initIsTranslating($form_state, $host);
$header_actions = $this
->buildHeaderActions($field_state, $form_state);
if ($header_actions) {
$elements['header_actions'] = $header_actions;
$elements['header_actions']['_weight'] = [
'#type' => 'weight',
'#default_value' => -100,
];
}
if (($this->realItemCount < $cardinality || $cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) && !$form_state
->isProgrammed() && $this
->allowReferenceChanges()) {
$elements['add_more'] = $this
->buildAddActions();
$elements['add_more']['#attributes']['class'][] = 'paragraphs-add-wrapper';
$elements['add_more']['add_more_delta'] = [
'#type' => 'hidden',
'#attributes' => [
'class' => [
'paragraph-type-add-delta',
$this
->getSetting('add_mode'),
],
],
];
}
$elements['#allow_reference_changes'] = $this
->allowReferenceChanges();
$elements['#paragraphs_widget'] = TRUE;
$elements['#attached']['library'][] = 'paragraphs/drupal.paragraphs.widget';
if (\Drupal::theme()
->getActiveTheme()
->getName() == 'seven') {
$elements['#attached']['library'][] = 'paragraphs/paragraphs.seven';
}
return $elements;
}
public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
$parents = $form['#parents'];
if (in_array('default_value_input', $parents, TRUE)) {
return [
'#markup' => $this
->t('No widget available for: %label.', [
'%label' => $items
->getFieldDefinition()
->getLabel(),
]),
];
}
$elements = parent::form($items, $form, $form_state, $get_delta);
$elements['#multilingual'] = TRUE;
return $elements;
}
protected function getChildParagraphs(FormStateInterface $form_state, $field_name, ParagraphInterface $paragraph = NULL, array $array_parents = []) {
$full_parents_key = [
'field_storage',
'#parents',
];
foreach ($array_parents as $i => $parent) {
$full_parents_key[] = $parent;
if ($i % 2) {
$full_parents_key[] = 'subform';
}
}
$current_parents = array_merge($full_parents_key, [
'#fields',
$field_name,
]);
$child_field_state = NestedArray::getValue($form_state
->getStorage(), $current_parents);
$entities = [];
if ($child_field_state && isset($child_field_state['paragraphs'])) {
$new_widget_paragraphs = [];
foreach ($child_field_state['paragraphs'] as $child_delta => $child_field_item_state) {
$entities[array_search($child_delta, $child_field_state['original_deltas'])] = $child_field_item_state['entity'];
$new_widget_paragraphs[array_search($child_delta, $child_field_state['original_deltas'])] = $child_field_item_state;
}
ksort($entities);
ksort($new_widget_paragraphs);
$child_field_state['paragraphs'] = $new_widget_paragraphs;
$child_field_state['original_deltas'] = range(0, count($child_field_state['paragraphs']) - 1);
NestedArray::setValue($form_state
->getStorage(), $current_parents, $child_field_state);
}
elseif ($paragraph) {
foreach ($paragraph
->get($field_name) as $child_delta => $item) {
if ($item->entity) {
$entities[$child_delta] = $item->entity;
}
}
}
return $entities;
}
protected function buildNestedParagraphsFoDragDrop(FormStateInterface $form_state, ParagraphInterface $paragraph = NULL, array $array_parents = []) {
$elements = [];
$field_definitions = [];
if ($paragraph) {
foreach ($paragraph
->getFieldDefinitions() as $child_field_name => $field_definition) {
if ($field_definition
->getType() == 'entity_reference_revisions' && $field_definition
->getSetting('target_type') == 'paragraph') {
$field_definitions[$child_field_name] = $field_definition;
}
}
}
else {
$field_definitions = [
$this->fieldDefinition
->getName() => $this->fieldDefinition,
];
}
foreach ($field_definitions as $child_field_name => $field_definition) {
$child_path = implode('][', array_merge($array_parents, [
$child_field_name,
]));
$cardinality = $field_definition
->getFieldStorageDefinition()
->getCardinality();
$allowed_types = implode(',', array_keys($this
->getAllowedTypes($field_definition)));
$elements[$child_field_name] = [
'#type' => 'container',
'#attributes' => [
'class' => [
'paragraphs-dragdrop-wrapper',
],
],
];
$label = count($field_definitions) > 1 || !$paragraph ? '<label><strong class="paragraphs-dragdrop__label paragraphs-dragdrop__label--field">' . $field_definition
->getLabel() . '</strong></label>' : '';
$elements[$child_field_name]['list'] = [
'#type' => 'markup',
'#prefix' => $label . '<ul class="paragraphs-dragdrop__list" data-paragraphs-dragdrop-cardinality="' . $cardinality . '" data-paragraphs-dragdrop-allowed-types="' . $allowed_types . '" data-paragraphs-dragdrop-path="' . $child_path . '">',
'#suffix' => '</ul>',
];
foreach ($this
->getChildParagraphs($form_state, $child_field_name, $paragraph, $array_parents) as $child_delta => $child_paragraph) {
$element = [];
$element['top'] = [
'#type' => 'container',
'#attributes' => [
'class' => [
'paragraphs-summary-wrapper',
],
],
];
$element['top']['paragraph_summary']['type'] = [
'#markup' => '<strong class="paragraphs-dragdrop__label paragraphs-dragdrop__label--bundle">' . $child_paragraph
->getParagraphType()
->label() . '</strong>',
];
$element['_weight'] = array(
'#type' => 'hidden',
'#default_value' => $child_delta,
'#attributes' => [
'class' => [
'paragraphs-dragdrop__weight',
],
],
);
$element['_path'] = [
'#type' => 'hidden',
'#title' => $this
->t('Current path for @number', [
'@number' => $delta = 1,
]),
'#title_display' => 'invisible',
'#default_value' => $child_path,
'#attributes' => [
'class' => [
'paragraphs-dragdrop__path',
],
],
];
$summary_options = [];
$element['#prefix'] = '<li class="paragraphs-dragdrop__item" data-paragraphs-dragdrop-bundle="' . $child_paragraph
->bundle() . '"><a href="#" class="paragraphs-dragdrop__handle"><span class="paragraphs-dragdrop__icon"></span></a>';
$element['#suffix'] = '</li>';
$child_array_parents = array_merge($array_parents, [
$child_field_name,
$child_delta,
]);
if ($child_elements = $this
->buildNestedParagraphsFoDragDrop($form_state, $child_paragraph, $child_array_parents)) {
$element['dragdrop'] = $child_elements;
$summary_options['depth_limit'] = 1;
}
$element['top']['summary']['fields_info'] = [
'#theme' => 'paragraphs_summary',
'#summary' => $child_paragraph
->getSummaryItems($summary_options),
'#expanded' => FALSE,
'#access' => $child_paragraph
->access('update') || $child_paragraph
->access('view'),
];
$info = $child_paragraph
->getIcons();
if (isset($info['count'])) {
$element['top']['icons']['count'] = $info['count'];
}
$elements[$child_field_name]['list'][$child_delta] = $element;
}
}
return $elements;
}
protected function buildAddActions() {
if (count($this
->getAccessibleOptions()) === 0) {
if (count($this
->getAllowedTypes()) === 0) {
$add_more_elements['icons'] = $this
->createMessage($this
->t('You are not allowed to add any of the @title types.', [
'@title' => $this
->getSetting('title'),
]));
}
else {
$add_more_elements['icons'] = $this
->createMessage($this
->t('You did not add any @title types yet.', [
'@title' => $this
->getSetting('title'),
]));
}
return $add_more_elements;
}
if (in_array($this
->getSetting('add_mode'), [
'button',
'dropdown',
'modal',
])) {
return $this
->buildButtonsAddMode();
}
return $this
->buildSelectAddMode();
}
protected function getAccessibleOptions() {
if ($this->accessOptions !== NULL) {
return $this->accessOptions;
}
$this->accessOptions = [];
$entity_type_manager = \Drupal::entityTypeManager();
$target_type = $this
->getFieldSetting('target_type');
$bundles = $this
->getAllowedTypes();
$access_control_handler = $entity_type_manager
->getAccessControlHandler($target_type);
$dragdrop_settings = $this
->getSelectionHandlerSetting('target_bundles_drag_drop');
foreach ($bundles as $machine_name => $bundle) {
if ($dragdrop_settings || (empty($this
->getSelectionHandlerSetting('target_bundles')) || in_array($machine_name, $this
->getSelectionHandlerSetting('target_bundles')))) {
if ($access_control_handler
->createAccess($machine_name)) {
$this->accessOptions[$machine_name] = $bundle['label'];
}
}
}
return $this->accessOptions;
}
public function createMessage($message, $type = 'warning') {
return [
'#type' => 'container',
'#markup' => $message,
'#attributes' => [
'class' => [
'messages',
'messages--' . $type,
],
],
];
}
public static function expandButton(array $button_base) {
if (empty($button_base['#submit'])) {
return $button_base;
}
$button = $button_base + [
'#type' => 'submit',
'#theme_wrappers' => [
'input__submit__paragraph_action',
],
];
$button['#name'] = strtr(Html::getId($button_base['#name']), '-', '_');
$button['#id'] = Html::getUniqueId($button['#name']);
if (isset($button['#ajax'])) {
$button['#ajax'] += [
'effect' => 'fade',
'progress' => [
'type' => 'fullscreen',
],
];
}
return $button;
}
public static function getSubmitElementInfo(array $form, FormStateInterface $form_state, $position = ParagraphsWidget::ACTION_POSITION_BASE) {
$submit['button'] = $form_state
->getTriggeringElement();
if ($position == ParagraphsWidget::ACTION_POSITION_BASE) {
$submit['element'] = NestedArray::getValue($form, array_slice($submit['button']['#array_parents'], 0, -2));
}
if ($position == ParagraphsWidget::ACTION_POSITION_HEADER) {
$submit['element'] = NestedArray::getValue($form, array_slice($submit['button']['#array_parents'], 0, -3));
}
elseif ($position == ParagraphsWidget::ACTION_POSITION_ACTIONS) {
$submit['element'] = NestedArray::getValue($form, array_slice($submit['button']['#array_parents'], 0, -5));
$delta = array_slice($submit['button']['#array_parents'], -5, -4);
$submit['delta'] = $delta[0];
}
$submit['field_name'] = $submit['element']['#field_name'];
$submit['parents'] = $submit['element']['#field_parents'];
$submit['widget_state'] = static::getWidgetState($submit['parents'], $submit['field_name'], $form_state);
return $submit;
}
protected function buildDropbutton(array $elements = []) {
$build = [
'#type' => 'container',
'#attributes' => [
'class' => [
'paragraphs-dropbutton-wrapper',
],
],
];
$operations = [];
foreach (Element::children($elements, TRUE) as $child) {
$operations[$child] = [
'title' => $elements[$child],
];
$elements[$child]['#printed'] = TRUE;
}
$build['operations'] = [
'#type' => 'paragraph_operations',
'#links' => $operations,
];
return $build + $elements;
}
protected function buildButtonsAddMode() {
$options = $this
->getAccessibleOptions();
$add_mode = $this
->getSetting('add_mode');
$paragraphs_type_storage = \Drupal::entityTypeManager()
->getStorage('paragraphs_type');
foreach ($options as $machine_name => $label) {
$button_key = 'add_more_button_' . $machine_name;
$add_more_elements[$button_key] = $this
->expandButton([
'#type' => 'submit',
'#name' => $this->fieldIdPrefix . '_' . $machine_name . '_add_more',
'#value' => $add_mode == 'modal' ? $label : $this
->t('Add @type', [
'@type' => $label,
]),
'#attributes' => [
'class' => [
'field-add-more-submit',
'button--small',
],
],
'#limit_validation_errors' => [
array_merge($this->fieldParents, [
$this->fieldDefinition
->getName(),
'add_more',
]),
],
'#submit' => [
[
get_class($this),
'addMoreSubmit',
],
],
'#ajax' => [
'callback' => [
get_class($this),
'addMoreAjax',
],
'wrapper' => $this->fieldWrapperId,
],
'#bundle_machine_name' => $machine_name,
]);
if ($add_mode === 'modal' && ($icon_url = $paragraphs_type_storage
->load($machine_name)
->getIconUrl())) {
$add_more_elements[$button_key]['#attributes']['style'] = 'background-image: url(' . $icon_url . ');';
}
}
if ($add_mode == 'dropdown') {
if (count($add_more_elements) > 1) {
$add_more_elements = $this
->buildDropbutton($add_more_elements);
}
else {
$add_more_elements['#attributes']['class'][] = 'paragraphs-dropbutton-wrapper';
}
$add_more_elements['#suffix'] = $this
->t('to %type', [
'%type' => $this->fieldDefinition
->getLabel(),
]);
}
elseif ($add_mode == 'modal') {
$this
->buildModalAddForm($add_more_elements);
$add_more_elements['add_modal_form_area']['#suffix'] = '<span class="paragraphs-add-suffix">' . $this
->t('to %type', [
'%type' => $this->fieldDefinition
->getLabel(),
]) . '</span>';
}
$add_more_elements['#type'] = 'container';
$add_more_elements['#weight'] = 1;
return $add_more_elements;
}
protected function buildSelectAddMode() {
$field_name = $this->fieldDefinition
->getName();
$field_title = $this->fieldDefinition
->getLabel();
$setting_title = $this
->getSetting('title');
$select_options = $this
->getAccessibleOptions();
$add_more_elements = [
'#type' => 'container',
];
$add_more_elements['add_more_select'] = [
'#type' => 'select',
'#options' => $select_options,
'#title' => $this
->t('@title type', [
'@title' => $setting_title,
]),
'#label_display' => 'hidden',
];
if (count($select_options) === 1) {
$add_more_elements['add_more_select']['#type'] = 'value';
$add_more_elements['add_more_select']['#value'] = key($select_options);
}
$text = $this
->t('Add @title', [
'@title' => $setting_title,
]);
if ($this->realItemCount > 0) {
$text = $this
->t('Add another @title', [
'@title' => $setting_title,
]);
}
$add_more_elements['add_more_button'] = [
'#type' => 'submit',
'#name' => strtr($this->fieldIdPrefix, '-', '_') . '_add_more',
'#value' => $text,
'#attributes' => [
'class' => [
'field-add-more-submit',
],
],
'#limit_validation_errors' => [
array_merge($this->fieldParents, [
$field_name,
'add_more',
]),
],
'#submit' => [
[
get_class($this),
'addMoreSubmit',
],
],
'#ajax' => [
'callback' => [
get_class($this),
'addMoreAjax',
],
'wrapper' => $this->fieldWrapperId,
'effect' => 'fade',
],
];
$add_more_elements['add_more_button']['#suffix'] = $this
->t(' to %type', [
'%type' => $field_title,
]);
return $add_more_elements;
}
public static function addMoreAjax(array $form, FormStateInterface $form_state) {
$submit = ParagraphsWidget::getSubmitElementInfo($form, $form_state);
$element = $submit['element'];
$delta = $submit['element']['#max_delta'];
$element[$delta]['#prefix'] = '<div class="ajax-new-content">' . (isset($element[$delta]['#prefix']) ? $element[$delta]['#prefix'] : '');
$element[$delta]['#suffix'] = (isset($element[$delta]['#suffix']) ? $element[$delta]['#suffix'] : '') . '</div>';
NestedArray::setValue($element, [
'add_more',
'add_more_delta',
'#value',
], '');
return $element;
}
public static function allActionsAjax(array $form, FormStateInterface $form_state) {
$submit = ParagraphsWidget::getSubmitElementInfo($form, $form_state, ParagraphsWidget::ACTION_POSITION_HEADER);
$element = $submit['element'];
$delta = $submit['element']['#max_delta'];
$element[$delta]['#prefix'] = '<div class="ajax-new-content">' . (isset($element[$delta]['#prefix']) ? $element[$delta]['#prefix'] : '');
$element[$delta]['#suffix'] = (isset($element[$delta]['#suffix']) ? $element[$delta]['#suffix'] : '') . '</div>';
return $element;
}
protected static function prepareDeltaPosition(array &$widget_state, FormStateInterface $form_state, array $field_path, $new_delta) {
$widget_state['items_count']++;
if (!is_numeric($new_delta) || intval($new_delta) >= $widget_state['real_item_count']) {
return;
}
$widget_state['real_item_count']++;
$new_delta = max(intval($new_delta), 0);
$user_input = NestedArray::getValue($form_state
->getUserInput(), $field_path);
$new_original_deltas = [];
foreach ($widget_state['original_deltas'] as $current_delta => $original_delta) {
$new_current_delta = $current_delta >= $new_delta ? $current_delta + 1 : $current_delta;
$new_original_deltas[$new_current_delta] = $original_delta;
$user_input[$original_delta]['_weight'] = $new_current_delta;
}
$original_deltas_size = count($widget_state['original_deltas']);
$new_original_deltas[$new_delta] = $original_deltas_size;
$user_input[$original_deltas_size]['_weight'] = $new_delta;
$widget_state['original_deltas'] = $new_original_deltas;
NestedArray::setValue($form_state
->getUserInput(), $field_path, $user_input);
}
public static function addMoreSubmit(array $form, FormStateInterface $form_state) {
$submit = ParagraphsWidget::getSubmitElementInfo($form, $form_state);
if ($submit['widget_state']['real_item_count'] < $submit['element']['#cardinality'] || $submit['element']['#cardinality'] == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
$field_path = array_merge($submit['element']['#field_parents'], [
$submit['element']['#field_name'],
]);
$add_more_delta = NestedArray::getValue($submit['element'], [
'add_more',
'add_more_delta',
'#value',
]);
static::prepareDeltaPosition($submit['widget_state'], $form_state, $field_path, $add_more_delta);
}
if (isset($submit['button']['#bundle_machine_name'])) {
$submit['widget_state']['selected_bundle'] = $submit['button']['#bundle_machine_name'];
}
else {
$submit['widget_state']['selected_bundle'] = $submit['element']['add_more']['add_more_select']['#value'];
}
$submit['widget_state'] = static::autocollapse($submit['widget_state']);
static::setWidgetState($submit['parents'], $submit['field_name'], $form_state, $submit['widget_state']);
$form_state
->setRebuild();
}
public static function duplicateSubmit(array $form, FormStateInterface $form_state) {
$button = $form_state
->getTriggeringElement();
$element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -5));
$field_name = $element['#field_name'];
$parents = $element['#field_parents'];
$filed_path = array_slice($button['#parents'], 0, -5);
$widget_state = static::getWidgetState($parents, $field_name, $form_state);
$original_button_delta = $button['#delta'];
$position = array_search($button['#delta'], $widget_state['original_deltas']) + 1;
static::prepareDeltaPosition($widget_state, $form_state, $filed_path, $position);
$entity = $widget_state['paragraphs'][$original_button_delta]['entity'];
$widget_state = static::autocollapse($widget_state);
if (\Drupal::hasService('replicate.replicator')) {
$duplicate_entity = \Drupal::getContainer()
->get('replicate.replicator')
->cloneEntity($entity);
}
else {
$duplicate_entity = $entity
->createDuplicate();
}
$widget_state['paragraphs'][] = [
'entity' => $duplicate_entity,
'display' => $widget_state['paragraphs'][$original_button_delta]['display'],
'mode' => 'edit',
];
static::setWidgetState($parents, $field_name, $form_state, $widget_state);
$form_state
->setRebuild();
}
public static function paragraphsItemSubmit(array $form, FormStateInterface $form_state) {
$submit = ParagraphsWidget::getSubmitElementInfo($form, $form_state, ParagraphsWidget::ACTION_POSITION_ACTIONS);
$new_mode = $submit['button']['#paragraphs_mode'];
if ($new_mode === 'edit') {
$submit['widget_state'] = static::autocollapse($submit['widget_state']);
}
$submit['widget_state']['paragraphs'][$submit['delta']]['mode'] = $new_mode;
if (!empty($submit['button']['#paragraphs_show_warning'])) {
$submit['widget_state']['paragraphs'][$submit['delta']]['show_warning'] = $submit['button']['#paragraphs_show_warning'];
}
static::setWidgetState($submit['parents'], $submit['field_name'], $form_state, $submit['widget_state']);
$form_state
->setRebuild();
}
public static function itemAjax(array $form, FormStateInterface $form_state) {
$submit = ParagraphsWidget::getSubmitElementInfo($form, $form_state, ParagraphsWidget::ACTION_POSITION_ACTIONS);
$submit['element']['#prefix'] = '<div class="ajax-new-content">' . (isset($submit['element']['#prefix']) ? $submit['element']['#prefix'] : '');
$submit['element']['#suffix'] = (isset($submit['element']['#suffix']) ? $submit['element']['#suffix'] : '') . '</div>';
return $submit['element'];
}
public static function dragDropModeSubmit(array $form, FormStateInterface $form_state) {
$submit = ParagraphsWidget::getSubmitElementInfo($form, $form_state, ParagraphsWidget::ACTION_POSITION_HEADER);
if (empty($submit['widget_state']['dragdrop'])) {
$submit['widget_state']['dragdrop'] = TRUE;
}
else {
$submit['widget_state']['dragdrop'] = FALSE;
}
unset($submit['widget_state']['reordered']);
static::setWidgetState($submit['parents'], $submit['field_name'], $form_state, $submit['widget_state']);
$form_state
->setRebuild();
}
protected static function reorderParagraphs(FormStateInterface $form_state, $field_values_parents) {
$field_name = end($field_values_parents);
$field_values = NestedArray::getValue($form_state
->getValues(), $field_values_parents);
$complete_field_storage = NestedArray::getValue($form_state
->getStorage(), [
'field_storage',
'#parents',
]);
$new_field_storage = $complete_field_storage;
if (!empty($new_field_storage['#fields'][$field_name]['reordered'])) {
return;
}
$new_field_storage['#fields'][$field_name]['reordered'] = TRUE;
$clear_paragraphs = function ($field_storage) use (&$clear_paragraphs) {
foreach ($field_storage as $key => $value) {
if ($key === '#fields') {
foreach ($value as $field_name => $widget_state) {
if (isset($widget_state['paragraphs'])) {
$field_storage['#fields'][$field_name]['paragraphs'] = [];
}
}
}
else {
$field_storage[$key] = $clear_paragraphs($field_storage[$key]);
}
}
return $field_storage;
};
$new_field_storage['#fields'][$field_name]['paragraphs'] = [];
if (isset($new_field_storage[$field_name])) {
$new_field_storage[$field_name] = $clear_paragraphs($new_field_storage[$field_name]);
}
$reorder_paragraphs = function ($reorder_values, $parents = [], FieldableEntityInterface $parent_entity = NULL) use ($complete_field_storage, &$new_field_storage, &$reorder_paragraphs) {
foreach ($reorder_values as $field_name => $values) {
foreach ($values['list'] as $delta => $item_values) {
$old_keys = array_merge($parents, [
'#fields',
$field_name,
'paragraphs',
$delta,
]);
$path = explode('][', $item_values['_path']);
$new_field_name = array_pop($path);
$key_parents = [];
foreach ($path as $i => $key) {
$key_parents[] = $key;
if ($i % 2 == 1) {
$key_parents[] = 'subform';
}
}
$new_keys = array_merge($key_parents, [
'#fields',
$new_field_name,
'paragraphs',
$item_values['_weight'],
]);
$key_exists = NULL;
$item_state = NestedArray::getValue($complete_field_storage, $old_keys, $key_exists);
if (!$key_exists && $parent_entity) {
$item_state = [
'entity' => $parent_entity
->get($field_name)
->get($delta)->entity,
'mode' => 'closed',
];
$widget_state_keys = array_slice($old_keys, 0, count($old_keys) - 2);
if (!NestedArray::getValue($new_field_storage, $widget_state_keys)) {
NestedArray::setValue($new_field_storage, $widget_state_keys, [
'paragraphs' => [],
]);
}
}
$item_state['entity']
->setNeedsSave(TRUE);
NestedArray::setValue($new_field_storage, $new_keys, $item_state);
if (isset($item_values['dragdrop'])) {
foreach (array_keys($item_values['dragdrop']) as $sub_field_name) {
$new_widget_state_keys = array_merge($parents, [
$field_name,
$item_values['_weight'],
'subform',
'#fields',
$sub_field_name,
]);
if (!NestedArray::getValue($new_field_storage, $new_widget_state_keys)) {
NestedArray::setValue($new_field_storage, $new_widget_state_keys, [
'paragraphs' => [],
]);
}
}
$reorder_paragraphs($item_values['dragdrop'], array_merge($parents, [
$field_name,
$delta,
'subform',
]), $item_state['entity']);
}
}
}
};
$reorder_paragraphs($field_values['dragdrop']);
$recalculate_original_deltas = function ($field_storage, ContentEntityInterface $parent_entity) use (&$recalculate_original_deltas) {
if (isset($field_storage['#fields'])) {
foreach ($field_storage['#fields'] as $field_name => $widget_state) {
if (isset($widget_state['paragraphs'])) {
if (!$parent_entity
->hasField($field_name) && !empty($widget_state['paragraphs'])) {
throw new \LogicException('Reordering paragraphs resulted in paragraphs on non-existing field ' . $field_name . ' on parent entity ' . $parent_entity
->getEntityTypeId() . '/' . $parent_entity
->id());
}
ksort($widget_state['paragraphs']);
$widget_state['paragraphs'] = array_values($widget_state['paragraphs']);
$original_deltas = range(0, count($widget_state['paragraphs']) - 1);
$field_storage['#fields'][$field_name]['original_deltas'] = $original_deltas;
$field_storage['#fields'][$field_name]['items_count'] = count($widget_state['paragraphs']);
$field_storage['#fields'][$field_name]['real_item_count'] = count($widget_state['paragraphs']);
if ($parent_entity
->hasField($field_name)) {
$parent_entity
->set($field_name, array_column($widget_state['paragraphs'], 'entity'));
foreach (array_keys($widget_state['paragraphs']) as $delta) {
if (isset($field_storage[$field_name][$delta]['subform'])) {
$field_storage[$field_name][$delta]['subform'] = $recalculate_original_deltas($field_storage[$field_name][$delta]['subform'], $parent_entity
->get($field_name)
->get($delta)->entity);
}
}
}
}
}
}
return $field_storage;
};
$parent_entity = $form_state
->getFormObject()
->getEntity();
$new_field_storage = $recalculate_original_deltas($new_field_storage, $parent_entity);
$form_state
->set([
'field_storage',
'#parents',
], $new_field_storage);
}
public static function dragDropModeAjax(array $form, FormStateInterface $form_state) {
$submit = ParagraphsWidget::getSubmitElementInfo($form, $form_state, ParagraphsWidget::ACTION_POSITION_HEADER);
$submit['element']['#prefix'] = '<div class="ajax-new-content">' . (isset($submit['element']['#prefix']) ? $submit['element']['#prefix'] : '');
$submit['element']['#suffix'] = (isset($submit['element']['#suffix']) ? $submit['element']['#suffix'] : '') . '</div>';
return $submit['element'];
}
protected function getSelectionHandlerSetting($setting_name) {
$settings = $this
->getFieldSetting('handler_settings');
return isset($settings[$setting_name]) ? $settings[$setting_name] : NULL;
}
public function elementValidate($element, FormStateInterface $form_state, $form) {
$field_name = $this->fieldDefinition
->getName();
$widget_state = static::getWidgetState($element['#field_parents'], $field_name, $form_state);
$delta = $element['#delta'];
if (isset($widget_state['paragraphs'][$delta]['entity'])) {
$entity = $widget_state['paragraphs'][$delta]['entity'];
$display = $widget_state['paragraphs'][$delta]['display'];
if ($widget_state['paragraphs'][$delta]['mode'] == 'edit') {
$display
->extractFormValues($entity, $element['subform'], $form_state);
$paragraphs_type = $entity
->getParagraphType();
if (\Drupal::currentUser()
->hasPermission('edit behavior plugin settings')) {
foreach ($paragraphs_type
->getEnabledBehaviorPlugins() as $plugin_id => $plugin_values) {
if (!empty($element['behavior_plugins'][$plugin_id])) {
$subform_state = SubformState::createForSubform($element['behavior_plugins'][$plugin_id], $form_state
->getCompleteForm(), $form_state);
$plugin_values
->validateBehaviorForm($entity, $element['behavior_plugins'][$plugin_id], $subform_state);
}
}
}
}
}
static::setWidgetState($element['#field_parents'], $field_name, $form_state, $widget_state);
}
public function flagErrors(FieldItemListInterface $items, ConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
$field_name = $this->fieldDefinition
->getName();
$field_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
if (!empty($field_state['dragdrop'])) {
if ($violations
->count()) {
$element = NestedArray::getValue($form_state
->getCompleteForm(), $field_state['array_parents']);
foreach ($violations as $violation) {
$form_state
->setError($element, $violation
->getMessage());
}
}
}
else {
return parent::flagErrors($items, $violations, $form, $form_state);
}
}
public function errorElement(array $element, ConstraintViolationInterface $error, array $form, FormStateInterface $form_state) {
if (!empty($error->arrayPropertyPath) && ($sub_element = NestedArray::getValue($element, $error->arrayPropertyPath))) {
return $sub_element;
}
return $element;
}
public function multipleElementValidate(array $elements, FormStateInterface $form_state, array $form) {
$field_name = $this->fieldDefinition
->getName();
$widget_state = static::getWidgetState($elements['#field_parents'], $field_name, $form_state);
if ($elements['#required'] && $widget_state['real_item_count'] < 1) {
$form_state
->setError($elements, $this
->t('@name field is required.', [
'@name' => $this->fieldDefinition
->getLabel(),
]));
}
static::setWidgetState($elements['#field_parents'], $field_name, $form_state, $widget_state);
}
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
$field_name = $this->fieldDefinition
->getName();
$widget_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
$element = NestedArray::getValue($form_state
->getCompleteForm(), $widget_state['array_parents']);
if (!empty($widget_state['dragdrop'])) {
$path = array_merge($form['#parents'], array(
$field_name,
));
static::reorderParagraphs($form_state, $path);
$widget_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
$values = [];
foreach ($widget_state['paragraphs'] as $delta => $paragraph_state) {
$values[$delta]['entity'] = $paragraph_state['entity'];
}
return $values;
}
foreach ($values as $delta => &$item) {
if (isset($widget_state['paragraphs'][$item['_original_delta']]['entity']) && $widget_state['paragraphs'][$item['_original_delta']]['mode'] != 'remove') {
$paragraphs_entity = $widget_state['paragraphs'][$item['_original_delta']]['entity'];
$display = $widget_state['paragraphs'][$item['_original_delta']]['display'];
if ($widget_state['paragraphs'][$item['_original_delta']]['mode'] == 'edit') {
$display
->extractFormValues($paragraphs_entity, $element[$item['_original_delta']]['subform'], $form_state);
}
$langcode_key = $paragraphs_entity
->getEntityType()
->getKey('langcode');
if ($paragraphs_entity
->get($langcode_key)->value != $form_state
->get('langcode')) {
if ($paragraphs_entity
->hasTranslation($form_state
->get('langcode'))) {
$paragraphs_entity = $paragraphs_entity
->getTranslation($form_state
->get('langcode'));
}
else {
$paragraphs_entity
->set($langcode_key, $form_state
->get('langcode'));
}
}
if (isset($item['behavior_plugins'])) {
$paragraphs_type = $paragraphs_entity
->getParagraphType();
foreach ($paragraphs_type
->getEnabledBehaviorPlugins() as $plugin_id => $plugin_values) {
if (!isset($item['behavior_plugins'][$plugin_id])) {
$item['behavior_plugins'][$plugin_id] = [];
}
$original_delta = $item['_original_delta'];
if (isset($element[$original_delta]) && isset($element[$original_delta]['behavior_plugins'][$plugin_id]) && $form_state
->getCompleteForm() && \Drupal::currentUser()
->hasPermission('edit behavior plugin settings')) {
$subform_state = SubformState::createForSubform($element[$original_delta]['behavior_plugins'][$plugin_id], $form_state
->getCompleteForm(), $form_state);
if (isset($item['behavior_plugins'][$plugin_id])) {
$plugin_values
->submitBehaviorForm($paragraphs_entity, $item['behavior_plugins'][$plugin_id], $subform_state);
}
}
}
}
if (!$form_state
->isValidationComplete() && $widget_state['paragraphs'][$item['_original_delta']]['mode'] === 'edit') {
$display
->validateFormValues($paragraphs_entity, $element[$item['_original_delta']]['subform'], $form_state);
}
elseif (!$form_state
->isValidationComplete() && $form_state
->getLimitValidationErrors() === NULL) {
$violations = $paragraphs_entity
->validate();
$violations
->filterByFieldAccess();
if (!empty($violations)) {
foreach ($violations as $violation) {
if (substr($violation
->getPropertyPath(), -7) === '.format') {
continue;
}
$form_state
->setError($element[$item['_original_delta']], $this
->t('Validation error on collapsed paragraph @path: @message', [
'@path' => $violation
->getPropertyPath(),
'@message' => $violation
->getMessage(),
]));
}
}
}
$paragraphs_entity
->setNeedsSave(TRUE);
$item['entity'] = $paragraphs_entity;
$item['target_id'] = $paragraphs_entity
->id();
$item['target_revision_id'] = $paragraphs_entity
->getRevisionId();
}
elseif (isset($widget_state['paragraphs'][$item['_original_delta']]['mode']) && $widget_state['paragraphs'][$item['_original_delta']]['mode'] == 'remove') {
$item['target_id'] = NULL;
$item['target_revision_id'] = NULL;
}
}
return $values;
}
public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state) {
$items
->filterEmptyItems();
$field_name = $this->fieldDefinition
->getName();
$path = array_merge($form['#parents'], array(
$field_name,
));
$form_state_variables = $form_state
->getValues();
$key_exists = NULL;
$values = NestedArray::getValue($form_state_variables, $path, $key_exists);
if ($key_exists) {
unset($values['header_actions']);
NestedArray::setValue($form_state_variables, $path, $values);
$form_state
->setValues($form_state_variables);
}
return parent::extractFormValues($items, $form, $form_state);
}
protected function initIsTranslating(FormStateInterface $form_state, ContentEntityInterface $host) {
if ($this->isTranslating != NULL) {
return;
}
$this->isTranslating = FALSE;
if (!$host
->isTranslatable()) {
return;
}
if (!$host
->getEntityType()
->hasKey('default_langcode')) {
return;
}
$default_langcode_key = $host
->getEntityType()
->getKey('default_langcode');
if (!$host
->hasField($default_langcode_key)) {
return;
}
if (!empty($form_state
->get('content_translation'))) {
$this->isTranslating = TRUE;
}
$langcode = $form_state
->get('langcode');
if ($host
->hasTranslation($langcode) && $host
->getTranslation($langcode)
->get($default_langcode_key)->value == 0) {
$this->isTranslating = TRUE;
}
}
public static function addTranslatabilityClue(array $element, FormStateInterface $form_state) {
static $suffix, $fapi_title_elements;
if (!isset($suffix)) {
$suffix = ' <span class="translation-entity-all-languages">(' . t('all languages') . ')</span>';
$fapi_title_elements = array_flip([
'checkbox',
'checkboxes',
'date',
'details',
'fieldset',
'file',
'item',
'password',
'password_confirm',
'radio',
'radios',
'select',
'textarea',
'textfield',
'weight',
]);
}
if (isset($element['#type']) && isset($fapi_title_elements[$element['#type']]) && isset($element['#title'])) {
$element['#title'] .= $suffix;
}
elseif ($children = Element::children($element)) {
foreach ($children as $delta) {
$element[$delta] = static::addTranslatabilityClue($element[$delta], $form_state);
}
}
elseif (isset($element['#title'])) {
$element['#title'] .= $suffix;
}
return $element;
}
protected function getDefaultParagraphTypeLabelName() {
if ($this
->getDefaultParagraphTypeMachineName() !== NULL) {
$allowed_types = $this
->getAllowedTypes();
return $allowed_types[$this
->getDefaultParagraphTypeMachineName()]['label'];
}
return NULL;
}
protected function getDefaultParagraphTypeMachineName() {
$default_type = $this
->getSetting('default_paragraph_type');
$allowed_types = $this
->getAllowedTypes();
if ($default_type && isset($allowed_types[$default_type])) {
return $default_type;
}
if ($default_type === '_none') {
return NULL;
}
if (count($allowed_types) === 1) {
return key($allowed_types);
}
return NULL;
}
protected function getNumberOfParagraphsInMode(array $widget_state, $mode) {
if (!isset($widget_state['paragraphs'])) {
return 0;
}
$paragraphs_count = 0;
foreach ($widget_state['paragraphs'] as $paragraph) {
if ($paragraph['mode'] == $mode) {
$paragraphs_count++;
}
}
return $paragraphs_count;
}
public static function isApplicable(FieldDefinitionInterface $field_definition) {
$target_type = $field_definition
->getSetting('target_type');
$paragraph_type = \Drupal::entityTypeManager()
->getDefinition($target_type);
if ($paragraph_type) {
return $paragraph_type
->entityClassImplements(ParagraphInterface::class);
}
return FALSE;
}
public function buildHeaderActions(array $field_state, FormStateInterface $form_state) {
$actions = [];
$field_name = $this->fieldDefinition
->getName();
$id_prefix = implode('-', array_merge($this->fieldParents, [
$field_name,
]));
if (empty($this->fieldParents)) {
$library_discovery = \Drupal::service('library.discovery');
$library = $library_discovery
->getLibraryByName('paragraphs', 'paragraphs-dragdrop');
if ($this->realItemCount > 0 && ($library || \Drupal::state()
->get('paragraphs_test_dragdrop_force_show', FALSE))) {
$actions['dropdown_actions']['dragdrop_mode'] = $this
->expandButton([
'#type' => 'submit',
'#name' => $this->fieldIdPrefix . '_dragdrop_mode',
'#value' => $this
->t('Drag & drop'),
'#attributes' => [
'class' => [
'field-dragdrop-mode-submit',
],
],
'#submit' => [
[
get_class($this),
'dragDropModeSubmit',
],
],
'#weight' => 8,
'#ajax' => [
'callback' => [
get_class($this),
'dragDropModeAjax',
],
'wrapper' => $this->fieldWrapperId,
],
'#limit_validation_errors' => [
array_merge($this->fieldParents, [
$field_name,
'dragdrop_mode',
]),
],
'#access' => $this
->allowReferenceChanges(),
]);
}
}
if ($this->fieldDefinition
->getType() == 'entity_reference_revisions' && $this->realItemCount > 1 && $this
->isFeatureEnabled('collapse_edit_all')) {
$collapse_all = $this
->expandButton([
'#type' => 'submit',
'#value' => $this
->t('Collapse all'),
'#submit' => [
[
get_class($this),
'changeAllEditModeSubmit',
],
],
'#name' => $id_prefix . '_collapse_all',
'#paragraphs_mode' => 'closed',
'#limit_validation_errors' => [
array_merge($this->fieldParents, [
$field_name,
'collapse_all',
]),
],
'#ajax' => [
'callback' => [
get_class($this),
'allActionsAjax',
],
'wrapper' => $this->fieldWrapperId,
],
'#weight' => -1,
'#paragraphs_show_warning' => TRUE,
]);
$edit_all = $this
->expandButton([
'#type' => 'submit',
'#value' => $this
->t('Edit all'),
'#submit' => [
[
get_class($this),
'changeAllEditModeSubmit',
],
],
'#name' => $id_prefix . '_edit-all',
'#paragraphs_mode' => 'edit',
'#limit_validation_errors' => [],
'#ajax' => [
'callback' => [
get_class($this),
'allActionsAjax',
],
'wrapper' => $this->fieldWrapperId,
],
]);
$mode = isset($field_state['paragraphs'][0]['mode']) ? $field_state['paragraphs'][0]['mode'] : $this->settings['edit_mode'];
if ($mode === 'closed') {
$edit_all['#attributes'] = [
'class' => [
'paragraphs-icon-button',
'paragraphs-icon-button-edit',
'button--extrasmall',
],
'title' => $this
->t('Edit all'),
];
$edit_all['#title'] = $this
->t('Edit All');
$actions['actions']['edit_all'] = $edit_all;
$actions['dropdown_actions']['collapse_all'] = $collapse_all;
}
else {
$collapse_all['#attributes'] = [
'class' => [
'paragraphs-icon-button',
'paragraphs-icon-button-collapse',
'button--extrasmall',
],
'title' => $this
->t('Collapse all'),
];
$actions['actions']['collapse_all'] = $collapse_all;
$actions['dropdown_actions']['edit_all'] = $edit_all;
}
}
if ($actions) {
$actions['#type'] = 'paragraphs_actions';
$actions['#paragraphs_header'] = TRUE;
}
return $actions;
}
public static function changeAllEditModeSubmit(array $form, FormStateInterface $form_state) {
$submit = ParagraphsWidget::getSubmitElementInfo($form, $form_state, ParagraphsWidget::ACTION_POSITION_HEADER);
foreach ($submit['widget_state']['paragraphs'] as $delta => &$paragraph) {
if ($submit['widget_state']['paragraphs'][$delta]['mode'] !== 'remove') {
$submit['widget_state']['paragraphs'][$delta]['mode'] = $submit['button']['#paragraphs_mode'];
if (!empty($submit['button']['#paragraphs_show_warning'])) {
$submit['widget_state']['paragraphs'][$delta]['show_warning'] = $submit['button']['#paragraphs_show_warning'];
}
}
}
if ($submit['widget_state']['autocollapse_default'] == 'all') {
if ($submit['button']['#paragraphs_mode'] === 'edit') {
$submit['widget_state']['autocollapse'] = 'none';
}
elseif ($submit['button']['#paragraphs_mode'] === 'closed') {
$submit['widget_state']['autocollapse'] = 'all';
}
}
static::setWidgetState($submit['parents'], $submit['field_name'], $form_state, $submit['widget_state']);
$form_state
->setRebuild();
}
public static function autocollapse(array $widget_state) {
if ($widget_state['real_item_count'] > 0 && $widget_state['autocollapse'] !== 'none') {
foreach ($widget_state['paragraphs'] as $delta => $value) {
if ($widget_state['paragraphs'][$delta]['mode'] === 'edit') {
$widget_state['paragraphs'][$delta]['mode'] = 'closed';
}
}
}
return $widget_state;
}
protected function allowReferenceChanges() {
return !$this->isTranslating;
}
protected function removeButtonAccess(ParagraphInterface $paragraph) {
if (!$paragraph
->isNew() && !$paragraph
->access('delete')) {
return FALSE;
}
if (!$this
->allowReferenceChanges()) {
return FALSE;
}
$field_required = $this->fieldDefinition
->isRequired();
$allowed_types = $this
->getAllowedTypes();
$cardinality = $this->fieldDefinition
->getFieldStorageDefinition()
->getCardinality();
if ($field_required && $cardinality == 1 && count($allowed_types) == 1) {
return FALSE;
}
return TRUE;
}
protected function duplicateButtonAccess(ParagraphInterface $paragraph) {
if (!$this
->isFeatureEnabled('duplicate')) {
return FALSE;
}
if (!$paragraph
->access('update')) {
return FALSE;
}
if (!$this
->allowReferenceChanges()) {
return FALSE;
}
$cardinality = $this->fieldDefinition
->getFieldStorageDefinition()
->getCardinality();
return !($cardinality !== FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && $this->realItemCount === $cardinality);
}
protected function isFeatureEnabled($feature) {
$features = $this
->getSetting('features');
if (!empty($features[$feature])) {
return TRUE;
}
return FALSE;
}
}