InlineParagraphsWidget.php 55.6 KB
Newer Older
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
1 2 3 4
<?php

namespace Drupal\paragraphs\Plugin\Field\FieldWidget;

5
use Drupal\Component\Utility\NestedArray;
Jeroen's avatar
Jeroen committed
6
use Drupal\Component\Utility\Html;
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
7
use Drupal\Core\Entity\Entity\EntityFormDisplay;
8
use Drupal\Core\Entity\EntityInterface;
9
use Drupal\Core\Field\FieldDefinitionInterface;
10
use Drupal\Core\Field\FieldFilteredMarkup;
11
use Drupal\Core\Field\FieldStorageDefinitionInterface;
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
12 13 14
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FieldItemListInterface;
15
use Drupal\Core\Render\Element;
16
use Drupal\paragraphs\ParagraphInterface;
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
17
use Symfony\Component\Validator\ConstraintViolationInterface;
18
use Drupal\paragraphs\Plugin\EntityReferenceSelection\ParagraphSelection;
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
19 20 21 22

/**
 * Plugin implementation of the 'entity_reference paragraphs' widget.
 *
23 24 25
 * We hide add / remove buttons when translating to avoid accidental loss of
 * data because these actions effect all languages.
 *
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
26 27
 * @FieldWidget(
 *   id = "entity_reference_paragraphs",
28 29
 *   label = @Translation("Paragraphs Classic"),
 *   description = @Translation("A paragraphs inline form widget."),
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
30
 *   field_types = {
31
 *     "entity_reference_revisions"
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
32 33 34 35 36
 *   }
 * )
 */
class InlineParagraphsWidget extends WidgetBase {

37 38 39 40 41
  /**
   * Indicates whether the current widget instance is in translation.
   *
   * @var bool
   */
42
  protected $isTranslating;
43

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  /**
   * Id to name ajax buttons that includes field parents and field name.
   *
   * @var string
   */
  protected $fieldIdPrefix;

  /**
   * Wrapper id to identify the paragraphs.
   *
   * @var string
   */
  protected $fieldWrapperId;

  /**
   * Number of paragraphs item on form.
   *
   * @var int
   */
  protected $realItemCount;

  /**
   * Parents for the current paragraph.
   *
   * @var array
   */
  protected $fieldParents;

  /**
   * Accessible paragraphs types.
   *
   * @var array
   */
  protected $accessOptions = NULL;

Jeroen's avatar
Jeroen committed
79 80 81 82 83
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
84 85 86 87 88
      'title' => t('Paragraph'),
      'title_plural' => t('Paragraphs'),
      'edit_mode' => 'open',
      'add_mode' => 'dropdown',
      'form_display_mode' => 'default',
89
      'default_paragraph_type' => '',
Jeroen's avatar
Jeroen committed
90 91 92
    );
  }

Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
93 94 95 96
  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
Jeroen's avatar
Jeroen committed
97 98 99 100
    $elements = array();

    $elements['title'] = array(
      '#type' => 'textfield',
101 102
      '#title' => $this->t('Paragraph Title'),
      '#description' => $this->t('Label to appear as title on the button as "Add new [title]", this label is translatable'),
Jeroen's avatar
Jeroen committed
103 104 105 106 107 108
      '#default_value' => $this->getSetting('title'),
      '#required' => TRUE,
    );

    $elements['title_plural'] = array(
      '#type' => 'textfield',
109 110
      '#title' => $this->t('Plural Paragraph Title'),
      '#description' => $this->t('Title in its plural form.'),
Jeroen's avatar
Jeroen committed
111 112 113 114 115 116
      '#default_value' => $this->getSetting('title_plural'),
      '#required' => TRUE,
    );

    $elements['edit_mode'] = array(
      '#type' => 'select',
117 118
      '#title' => $this->t('Edit mode'),
      '#description' => $this->t('The mode the paragraph is in by default. Preview will render the paragraph in the preview view mode.'),
Jeroen's avatar
Jeroen committed
119
      '#options' => array(
120 121 122
        'open' => $this->t('Open'),
        'closed' => $this->t('Closed'),
        'preview' => $this->t('Preview'),
Jeroen's avatar
Jeroen committed
123 124 125 126 127 128 129
      ),
      '#default_value' => $this->getSetting('edit_mode'),
      '#required' => TRUE,
    );

    $elements['add_mode'] = array(
      '#type' => 'select',
130
      '#title' => $this->t('Add mode'),
131
      '#description' => $this->t('The way to add new Paragraphs.'),
Jeroen's avatar
Jeroen committed
132
      '#options' => array(
133 134 135
        'select' => $this->t('Select list'),
        'button' => $this->t('Buttons'),
        'dropdown' => $this->t('Dropdown button')
Jeroen's avatar
Jeroen committed
136 137 138 139 140 141 142
      ),
      '#default_value' => $this->getSetting('add_mode'),
      '#required' => TRUE,
    );

    $elements['form_display_mode'] = array(
      '#type' => 'select',
143
      '#options' => \Drupal::service('entity_display.repository')->getFormModeOptions($this->getFieldSetting('target_type')),
144 145
      '#description' => $this->t('The form display mode to use when rendering the paragraph form.'),
      '#title' => $this->t('Form display mode'),
Jeroen's avatar
Jeroen committed
146 147 148 149
      '#default_value' => $this->getSetting('form_display_mode'),
      '#required' => TRUE,
    );

150 151 152 153 154 155 156 157
    $options  = [];
    foreach ($this->getAllowedTypes() as $key => $bundle) {
      $options[$key] = $bundle['label'];
    }

    $elements['default_paragraph_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Default paragraph type'),
158
      '#empty_value' => '_none',
159 160 161 162 163
      '#default_value' => $this->getDefaultParagraphTypeMachineName(),
      '#options' => $options,
      '#description' => $this->t('When creating a new host entity, a paragraph of this type is added.'),
    ];

Jeroen's avatar
Jeroen committed
164
    return $elements;
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
165 166 167 168 169 170 171
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();
172 173 174 175
    $summary[] = $this->t('Title: @title', ['@title' => $this->getSetting('title')]);
    $summary[] = $this->t('Plural title: @title_plural', [
      '@title_plural' => $this->getSetting('title_plural')
    ]);
176 177 178 179

    switch($this->getSetting('edit_mode')) {
      case 'open':
      default:
180
        $edit_mode = $this->t('Open');
181 182
        break;
      case 'closed':
183
        $edit_mode = $this->t('Closed');
184 185
        break;
      case 'preview':
186
        $edit_mode = $this->t('Preview');
187 188 189 190 191 192
        break;
    }

    switch($this->getSetting('add_mode')) {
      case 'select':
      default:
193
        $add_mode = $this->t('Select list');
194 195
        break;
      case 'button':
196
        $add_mode = $this->t('Buttons');
197
        break;
Jeroen's avatar
Jeroen committed
198
      case 'dropdown':
199
        $add_mode = $this->t('Dropdown button');
Jeroen's avatar
Jeroen committed
200
        break;
201 202
    }

203 204 205 206 207 208 209 210 211 212 213
    $summary[] = $this->t('Edit mode: @edit_mode', ['@edit_mode' => $edit_mode]);
    $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()
      ]);
    }

Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
214 215 216 217 218
    return $summary;
  }

  /**
   * {@inheritdoc}
219 220 221
   *
   * @see \Drupal\content_translation\Controller\ContentTranslationController::prepareTranslation()
   *   Uses a similar approach to populate a new translation.
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
222 223
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
224
    $field_name = $this->fieldDefinition->getName();
Jeroen's avatar
Jeroen committed
225
    $parents = $element['#field_parents'];
226
    $info = [];
227

228
    /** @var \Drupal\paragraphs\ParagraphInterface $paragraphs_entity */
Jeroen's avatar
Jeroen committed
229
    $paragraphs_entity = NULL;
230
    $host = $items->getEntity();
231
    $widget_state = static::getWidgetState($parents, $field_name, $form_state);
232

233
    $entity_type_manager = \Drupal::entityTypeManager();
234 235
    $target_type = $this->getFieldSetting('target_type');

236
    $item_mode = isset($widget_state['paragraphs'][$delta]['mode']) ? $widget_state['paragraphs'][$delta]['mode'] : 'edit';
237
    $default_edit_mode = $this->getSetting('edit_mode');
238

239
    $show_must_be_saved_warning = !empty($widget_state['paragraphs'][$delta]['show_warning']);
240 241 242 243

    if (isset($widget_state['paragraphs'][$delta]['entity'])) {
      $paragraphs_entity = $widget_state['paragraphs'][$delta]['entity'];
    }
244
    elseif (isset($items[$delta]->entity)) {
245
      $paragraphs_entity = $items[$delta]->entity;
246 247 248 249 250 251 252 253 254 255 256 257 258 259

      // We don't have a widget state yet, get from selector settings.
      if (!isset($widget_state['paragraphs'][$delta]['mode'])) {

        if ($default_edit_mode == 'open') {
          $item_mode = 'edit';
        }
        elseif ($default_edit_mode == 'closed') {
          $item_mode = 'closed';
        }
        elseif ($default_edit_mode == 'preview') {
          $item_mode = 'preview';
        }
      }
260 261
    }
    elseif (isset($widget_state['selected_bundle'])) {
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
262

263
      $entity_type = $entity_type_manager->getDefinition($target_type);
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
264
      $bundle_key = $entity_type->getKey('bundle');
265

266
      $paragraphs_entity = $entity_type_manager->getStorage($target_type)->create(array(
267 268
        $bundle_key => $widget_state['selected_bundle'],
      ));
269
      $paragraphs_entity->setParentEntity($items->getEntity(), $field_name);
270 271

      $item_mode = 'edit';
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
272 273
    }

274 275 276 277
    if ($item_mode == 'collapsed') {
      $item_mode = $default_edit_mode;
    }

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    if ($item_mode == 'closed') {
      // Validate closed paragraphs and expand if needed.
      // @todo Consider recursion.
      $violations = $paragraphs_entity->validate();
      $violations->filterByFieldAccess();
      if (count($violations) > 0) {
        $item_mode = 'edit';
        $messages = [];
        foreach ($violations as $violation) {
          $messages[] = $violation->getMessage();
        }
        $info['validation_error'] = array(
          '#type' => 'container',
          '#markup' => $this->t('@messages', ['@messages' => strip_tags(implode('\n', $messages))]),
          '#attributes' => ['class' => ['messages', 'messages--warning']],
        );
      }
    }

297
    if ($paragraphs_entity) {
298 299 300
      // Detect if we are translating.
      $this->initIsTranslating($form_state, $host);
      $langcode = $form_state->get('langcode');
301

302 303
      if (!$this->isTranslating) {
        // Set the langcode if we are not translating.
304 305
        $langcode_key = $paragraphs_entity->getEntityType()->getKey('langcode');
        if ($paragraphs_entity->get($langcode_key)->value != $langcode) {
306 307 308 309 310 311
          // If a translation in the given language already exists, switch to
          // that. If there is none yet, update the language.
          if ($paragraphs_entity->hasTranslation($langcode)) {
            $paragraphs_entity = $paragraphs_entity->getTranslation($langcode);
          }
          else {
312
            $paragraphs_entity->set($langcode_key, $langcode);
313 314
          }
        }
315 316 317 318
      }
      else {
        // Add translation if missing for the target language.
        if (!$paragraphs_entity->hasTranslation($langcode)) {
319 320 321 322
          // Get the selected translation of the paragraph entity.
          $entity_langcode = $paragraphs_entity->language()->getId();
          $source = $form_state->get(['content_translation', 'source']);
          $source_langcode = $source ? $source->getId() : $entity_langcode;
323 324 325 326 327 328 329
          // Make sure the source language version is used if available. It is a
          // valid scenario to have no paragraphs items in the source version of
          // the host and fetching the translation without this check could lead
          // to an exception.
          if ($paragraphs_entity->hasTranslation($source_langcode)) {
            $paragraphs_entity = $paragraphs_entity->getTranslation($source_langcode);
          }
330 331 332 333 334 335 336 337 338 339 340 341 342 343
          // The paragraphs entity has no content translation source field if
          // no paragraph entity field is translatable, even if the host is.
          if ($paragraphs_entity->hasField('content_translation_source')) {
            // Initialise the translation with source language values.
            $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 any paragraphs type is translatable do not switch.
        if ($paragraphs_entity->hasField('content_translation_source')) {
          // Switch the paragraph to the translation.
          $paragraphs_entity = $paragraphs_entity->getTranslation($langcode);
344
        }
345
      }
346

Jeroen's avatar
Jeroen committed
347 348 349 350 351
      $element_parents = $parents;
      $element_parents[] = $field_name;
      $element_parents[] = $delta;
      $element_parents[] = 'subform';

352
      $id_prefix = implode('-', array_merge($parents, array($field_name, $delta)));
Jeroen's avatar
Jeroen committed
353
      $wrapper_id = Html::getUniqueId($id_prefix . '-item-wrapper');
354

355 356
      $element += array(
        '#type' => 'container',
Jeroen's avatar
Jeroen committed
357
        '#element_validate' => array(array($this, 'elementValidate')),
358
        '#paragraph_type' => $paragraphs_entity->bundle(),
359
        'subform' => array(
360
          '#type' => 'container',
Jeroen's avatar
Jeroen committed
361
          '#parents' => $element_parents,
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
362
        ),
363
      );
364

365 366 367
      $element['#prefix'] = '<div id="' . $wrapper_id . '">';
      $element['#suffix'] = '</div>';

368
      $item_bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo($target_type);
369 370
      if (isset($item_bundles[$paragraphs_entity->bundle()])) {
        $bundle_info = $item_bundles[$paragraphs_entity->bundle()];
Jeroen's avatar
Jeroen committed
371 372

        $element['top'] = array(
373 374
          '#type' => 'container',
          '#weight' => -1000,
Jeroen's avatar
Jeroen committed
375 376
          '#attributes' => array(
            'class' => array(
Jeroen's avatar
Jeroen committed
377
              'paragraph-type-top',
Jeroen's avatar
Jeroen committed
378 379
            ),
          ),
380
        );
Jeroen's avatar
Jeroen committed
381

Jeroen's avatar
Jeroen committed
382
        $element['top']['paragraph_type_title'] = array(
Jeroen's avatar
Jeroen committed
383 384 385 386
          '#type' => 'container',
          '#weight' => 0,
          '#attributes' => array(
            'class' => array(
Jeroen's avatar
Jeroen committed
387
              'paragraph-type-title',
Jeroen's avatar
Jeroen committed
388 389
            ),
          ),
390
        );
391

Jeroen's avatar
Jeroen committed
392
        $element['top']['paragraph_type_title']['info'] = array(
393
          '#markup' => $bundle_info['label'],
394 395
        );

Jeroen's avatar
Jeroen committed
396 397 398
        $actions = array();
        $links = array();

399 400
        // Avoid checking delete access for new entities.
        $delete_access = $paragraphs_entity->isNew() || $paragraphs_entity->access('delete');
401
        // Hide the button when translating.
402
        $button_access = $delete_access && !$this->isTranslating;
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
        if ($item_mode != 'remove') {
          $links['remove_button'] = [
            '#type' => 'submit',
            '#value' => $this->t('Remove'),
            '#name' => strtr($id_prefix, '-', '_') . '_remove',
            '#weight' => 501,
            '#submit' => [[get_class($this), 'paragraphsItemSubmit']],
            '#limit_validation_errors' => [array_merge($parents, [$field_name, 'add_more'])],
            '#delta' => $delta,
            '#ajax' => [
              'callback' => [get_class($this), 'itemAjax'],
              'wrapper' => $widget_state['ajax_wrapper_id'],
              'effect' => 'fade',
            ],
            '#access' => $button_access,
            '#prefix' => '<li class="remove">',
            '#suffix' => '</li>',
            '#paragraphs_mode' => 'remove',
          ];

        }
424

425
        if ($item_mode == 'edit') {
426

427 428 429
          if (isset($items[$delta]->entity) && ($default_edit_mode == 'preview' || $default_edit_mode == 'closed')) {
            $links['collapse_button'] = array(
              '#type' => 'submit',
430
              '#value' => $this->t('Collapse'),
431 432
              '#name' => strtr($id_prefix, '-', '_') . '_collapse',
              '#weight' => 499,
433
              '#submit' => array(array(get_class($this), 'paragraphsItemSubmit')),
434
              '#delta' => $delta,
435
              '#limit_validation_errors' => [array_merge($parents, [$field_name, 'add_more'])],
436 437 438 439 440 441 442 443
              '#ajax' => array(
                'callback' => array(get_class($this), 'itemAjax'),
                'wrapper' => $widget_state['ajax_wrapper_id'],
                'effect' => 'fade',
              ),
              '#access' => $paragraphs_entity->access('update'),
              '#prefix' => '<li class="collapse">',
              '#suffix' => '</li>',
444
              '#paragraphs_mode' => 'collapsed',
445
              '#paragraphs_show_warning' => TRUE,
446 447 448
            );
          }

Jeroen's avatar
Jeroen committed
449
          $info['edit_button_info'] = array(
450 451 452
            '#type' => 'container',
            '#markup' => $this->t('You are not allowed to edit this @title.', array('@title' => $this->getSetting('title'))),
            '#attributes' => ['class' => ['messages', 'messages--warning']],
453
            '#access' => !$paragraphs_entity->access('update') && $delete_access,
454
          );
455

Jeroen's avatar
Jeroen committed
456
          $info['remove_button_info'] = array(
457 458 459
            '#type' => 'container',
            '#markup' => $this->t('You are not allowed to remove this @title.', array('@title' => $this->getSetting('title'))),
            '#attributes' => ['class' => ['messages', 'messages--warning']],
460
            '#access' => !$delete_access && $paragraphs_entity->access('update'),
Jeroen's avatar
Jeroen committed
461 462 463
          );

          $info['edit_remove_button_info'] = array(
464 465 466
            '#type' => 'container',
            '#markup' => $this->t('You are not allowed to edit or remove this @title.', array('@title' => $this->getSetting('title'))),
            '#attributes' => ['class' => ['messages', 'messages--warning']],
467
            '#access' => !$paragraphs_entity->access('update') && !$delete_access,
468
          );
469
        }
470
        elseif ($item_mode == 'preview' || $item_mode == 'closed') {
471
          $links['edit_button'] = array(
472
            '#type' => 'submit',
473
            '#value' => $this->t('Edit'),
474
            '#name' => strtr($id_prefix, '-', '_') . '_edit',
475
            '#weight' => 500,
476
            '#submit' => array(array(get_class($this), 'paragraphsItemSubmit')),
Jeroen's avatar
Jeroen committed
477
            '#limit_validation_errors' => array(array_merge($parents, array($field_name, 'add_more'))),
478 479
            '#delta' => $delta,
            '#ajax' => array(
480
              'callback' => array(get_class($this), 'itemAjax'),
481
              'wrapper' => $widget_state['ajax_wrapper_id'],
482 483
              'effect' => 'fade',
            ),
484 485
            '#access' => $paragraphs_entity->access('update'),
            '#prefix' => '<li class="edit">',
Jeroen's avatar
Jeroen committed
486
            '#suffix' => '</li>',
487
            '#paragraphs_mode' => 'edit',
488
          );
489

490 491
          if ($show_must_be_saved_warning) {
            $info['must_be_saved_info'] = array(
492 493 494
              '#type' => 'container',
              '#markup' => $this->t('You have unsaved changes on this @title item.', array('@title' => $this->getSetting('title'))),
              '#attributes' => ['class' => ['messages', 'messages--warning']],
495 496 497
            );
          }

Jeroen's avatar
Jeroen committed
498
          $info['preview_info'] = array(
499 500 501
            '#type' => 'container',
            '#markup' => $this->t('You are not allowed to view this @title.', array('@title' => $this->getSetting('title'))),
            '#attributes' => ['class' => ['messages', 'messages--warning']],
Jeroen's avatar
Jeroen committed
502 503 504 505
            '#access' => !$paragraphs_entity->access('view'),
          );

          $info['edit_button_info'] = array(
506 507 508
            '#type' => 'container',
            '#markup' => $this->t('You are not allowed to edit this @title.', array('@title' => $this->getSetting('title'))),
            '#attributes' => ['class' => ['messages', 'messages--warning']],
509
            '#access' => !$paragraphs_entity->access('update') && $delete_access,
510
          );
511

Jeroen's avatar
Jeroen committed
512
          $info['remove_button_info'] = array(
513 514 515
            '#type' => 'container',
            '#markup' => $this->t('You are not allowed to remove this @title.', array('@title' => $this->getSetting('title'))),
            '#attributes' => ['class' => ['messages', 'messages--warning']],
516
            '#access' => !$delete_access && $paragraphs_entity->access('update'),
517 518
          );

Jeroen's avatar
Jeroen committed
519
          $info['edit_remove_button_info'] = array(
520 521 522
            '#type' => 'container',
            '#markup' => $this->t('You are not allowed to edit or remove this @title.', array('@title' => $this->getSetting('title'))),
            '#attributes' => ['class' => ['messages', 'messages--warning']],
523
            '#access' => !$paragraphs_entity->access('update') && !$delete_access,
524
          );
525
        }
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
        elseif ($item_mode == 'remove') {

          $element['top']['paragraph_type_title']['info'] = [
            '#markup' => $this->t('Deleted @title: %type', ['@title' => $this->getSetting('title'), '%type' => $bundle_info['label']]),
          ];

          $links['confirm_remove_button'] = [
            '#type' => 'submit',
            '#value' => $this->t('Confirm removal'),
            '#name' => strtr($id_prefix, '-', '_') . '_confirm_remove',
            '#weight' => 503,
            '#submit' => [[get_class($this), 'paragraphsItemSubmit']],
            '#limit_validation_errors' => [array_merge($parents, [$field_name, 'add_more'])],
            '#delta' => $delta,
            '#ajax' => [
              'callback' => [get_class($this), 'itemAjax'],
              'wrapper' => $widget_state['ajax_wrapper_id'],
              'effect' => 'fade',
            ],
            '#prefix' => '<li class="confirm-remove">',
            '#suffix' => '</li>',
            '#paragraphs_mode' => 'removed',
          ];

          $links['restore_button'] = [
            '#type' => 'submit',
            '#value' => $this->t('Restore'),
            '#name' => strtr($id_prefix, '-', '_') . '_restore',
            '#weight' => 504,
            '#submit' => [[get_class($this), 'paragraphsItemSubmit']],
            '#limit_validation_errors' => [array_merge($parents, [$field_name, 'add_more'])],
            '#delta' => $delta,
            '#ajax' => [
              'callback' => [get_class($this), 'itemAjax'],
              'wrapper' => $widget_state['ajax_wrapper_id'],
              'effect' => 'fade',
            ],
            '#prefix' => '<li class="restore">',
            '#suffix' => '</li>',
            '#paragraphs_mode' => 'edit',
          ];
        }
Jeroen's avatar
Jeroen committed
568

569
        if (!empty($links)) {
Jeroen's avatar
Jeroen committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583
          $show_links = 0;
          foreach($links as $link_item) {
            if (!isset($link_item['#access']) || $link_item['#access']) {
              $show_links++;
            }
          }

          if ($show_links > 0) {

            $element['top']['links'] = $links;
            if ($show_links > 1) {
              $element['top']['links']['#theme_wrappers'] = array('dropbutton_wrapper', 'paragraphs_dropbutton_wrapper');
              $element['top']['links']['prefix'] = array(
                '#markup' => '<ul class="dropbutton">',
584
                '#weight' => -999,
Jeroen's avatar
Jeroen committed
585 586 587
              );
              $element['top']['links']['suffix'] = array(
                '#markup' => '</li>',
588
                '#weight' => 999,
Jeroen's avatar
Jeroen committed
589 590 591 592 593 594 595 596 597
              );
            }
            else {
              $element['top']['links']['#theme_wrappers'] = array('paragraphs_dropbutton_wrapper');
              foreach($links as $key => $link_item) {
                unset($element['top']['links'][$key]['#prefix']);
                unset($element['top']['links'][$key]['#suffix']);
              }
            }
598
            $element['top']['links']['#weight'] = 2;
Jeroen's avatar
Jeroen committed
599 600 601
          }
        }

602
        if (!empty($info)) {
Jeroen's avatar
Jeroen committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616
          $show_info = FALSE;
          foreach($info as $info_item) {
            if (!isset($info_item['#access']) || $info_item['#access']) {
              $show_info = TRUE;
              break;
            }
          }

          if ($show_info) {
            $element['info'] = $info;
            $element['info']['#weight'] = 998;
          }
        }

617
        if (!empty($actions)) {
Jeroen's avatar
Jeroen committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631
          $show_actions = FALSE;
          foreach($actions as $action_item) {
            if (!isset($action_item['#access']) || $action_item['#access']) {
              $show_actions = TRUE;
              break;
            }
          }

          if ($show_actions) {
            $element['actions'] = $actions;
            $element['actions']['#type'] = 'actions';
            $element['actions']['#weight'] = 999;
          }
        }
632 633
      }

Jeroen's avatar
Jeroen committed
634
      $display = EntityFormDisplay::collectRenderDisplay($paragraphs_entity, $this->getSetting('form_display_mode'));
Jeroen's avatar
Jeroen committed
635

636 637 638 639 640 641 642 643 644 645 646 647
      // @todo Remove as part of https://www.drupal.org/node/2640056
      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);
648 649 650 651 652 653
        if (function_exists('field_group_form_pre_render')) {
          $element['subform']['#pre_render'][] = 'field_group_form_pre_render';
        }
        if (function_exists('field_group_form_process')) {
          $element['subform']['#process'][] = 'field_group_form_process';
        }
654 655
      }

656 657
      if ($item_mode == 'edit') {
        $display->buildForm($paragraphs_entity, $element['subform'], $form_state);
658
        $hide_untranslatable_fields = $paragraphs_entity->isDefaultTranslationAffectedOnly();
659 660
        foreach (Element::children($element['subform']) as $field) {
          if ($paragraphs_entity->hasField($field)) {
661
            $field_definition = $paragraphs_entity->getFieldDefinition($field);
662
            $translatable = $paragraphs_entity->{$field}->getFieldDefinition()->isTranslatable();
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689

            // Do a check if we have to add a class to the form element. We need
            // those classes (paragraphs-content and paragraphs-behavior) to show
            // and hide elements, depending of the active perspective.
            // We need them to filter out entity reference revisions fields that
            // reference paragraphs, cause otherwise we have problems with showing
            // and hiding the right fields in nested paragraphs.
            $is_paragraph_field = FALSE;
            if ($field_definition->getType() == 'entity_reference_revisions') {
              // Check if we are referencing paragraphs.
              if ($field_definition->getSetting('target_type') == 'paragraph') {
                $is_paragraph_field = TRUE;
              }
            }

            // Hide untranslatable fields when configured to do so except
            // paragraph fields.
            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'
                ];
              }
690 691 692
            }
          }
        }
693
      }
694 695
      elseif ($item_mode == 'preview') {
        $element['subform'] = array();
696
        $element['behavior_plugins'] = [];
697
        $element['preview'] = entity_view($paragraphs_entity, 'preview', $paragraphs_entity->language()->getId());
698
        $element['preview']['#access'] = $paragraphs_entity->access('view');
699 700 701
      }
      elseif ($item_mode == 'closed') {
        $element['subform'] = array();
702
        $element['behavior_plugins'] = [];
703 704
        if ($paragraphs_entity) {
          $element['top']['paragraph_summary']['fields_info'] = [
705 706
            '#theme' => 'paragraphs_summary',
            '#summary' => $paragraphs_entity->getSummaryItems(),
707 708
          ];
        }
709
      }
710 711 712
      else {
        $element['subform'] = array();
      }
713

Jeroen's avatar
Jeroen committed
714
      $element['subform']['#attributes']['class'][] = 'paragraphs-subform';
715 716
      $element['subform']['#access'] = $paragraphs_entity->access('update');

717
      if ($item_mode == 'removed') {
718 719 720
        $element['#access'] = FALSE;
      }

721 722 723
      $widget_state['paragraphs'][$delta]['entity'] = $paragraphs_entity;
      $widget_state['paragraphs'][$delta]['display'] = $display;
      $widget_state['paragraphs'][$delta]['mode'] = $item_mode;
724

Jeroen's avatar
Jeroen committed
725
      static::setWidgetState($parents, $field_name, $form_state, $widget_state);
726
    }
727 728 729
    else {
      $element['#access'] = FALSE;
    }
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
730

Jeroen's avatar
Jeroen committed
731
    return $element;
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
732 733
  }

734 735 736 737 738 739 740 741
  /**
   * Returns the sorted allowed types for a entity reference field.
   *
   * @return array
   *   A list of arrays keyed by the paragraph type machine name with the following properties.
   *     - label: The label of the paragraph type.
   *     - weight: The weight of the paragraph type.
   */
Jeroen's avatar
Jeroen committed
742
  public function getAllowedTypes() {
743 744

    $return_bundles = array();
745 746 747 748 749
    /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface $selection_manager */
    $selection_manager = \Drupal::service('plugin.manager.entity_reference_selection');
    $handler = $selection_manager->getSelectionHandler($this->fieldDefinition);
    if ($handler instanceof ParagraphSelection) {
      $return_bundles = $handler->getSortedAllowedTypes();
750 751 752
    }
    // Support for other reference types.
    else {
753
      $bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo($this->getFieldSetting('target_type'));
754 755
      $weight = 0;
      foreach ($bundles as $machine_name => $bundle) {
756
        if (empty($this->getSelectionHandlerSetting('target_bundles'))
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
          || in_array($machine_name, $this->getSelectionHandlerSetting('target_bundles'))) {

          $return_bundles[$machine_name] = array(
            'label' => $bundle['label'],
            'weight' => $weight,
          );

          $weight++;
        }
      }
    }

    return $return_bundles;
  }

772
  public function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
Jeroen's avatar
Jeroen committed
773 774
    $field_name = $this->fieldDefinition->getName();
    $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
775 776
    $this->fieldParents = $form['#parents'];
    $field_state = static::getWidgetState($this->fieldParents, $field_name, $form_state);
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
777

778
    $max = $field_state['items_count'];
779 780 781 782 783 784 785 786 787 788 789 790 791
    $entity_type_manager = \Drupal::entityTypeManager();

    // Consider adding a default paragraph for new host entities.
    if ($max == 0 && $items->getEntity()->isNew()) {
      $default_type = $this->getDefaultParagraphTypeMachineName();

      // Checking if default_type is not none and if is allowed.
      if ($default_type) {
        // Place the default paragraph.
        $target_type = $this->getFieldSetting('target_type');
        $paragraphs_entity = $entity_type_manager->getStorage($target_type)->create([
          'type' => $default_type,
        ]);
792
        $paragraphs_entity->setParentEntity($items->getEntity(), $field_name);
793 794 795 796 797 798 799 800 801 802 803 804 805
        $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;
      }
    }

806
    $this->realItemCount = $max;
Jeroen's avatar
Jeroen committed
807
    $is_multiple = $this->fieldDefinition->getFieldStorageDefinition()->isMultiple();
808

809 810
    $title = $this->fieldDefinition->getLabel();
    $description = FieldFilteredMarkup::create(\Drupal::token()->replace($this->fieldDefinition->getDescription()));
811 812

    $elements = array();
813 814 815
    $this->fieldIdPrefix = implode('-', array_merge($this->fieldParents, array($field_name)));
    $this->fieldWrapperId = Html::getUniqueId($this->fieldIdPrefix . '-add-more-wrapper');
    $elements['#prefix'] = '<div id="' . $this->fieldWrapperId . '">';
816 817
    $elements['#suffix'] = '</div>';

818
    $field_state['ajax_wrapper_id'] = $this->fieldWrapperId;
819
    // Persist the widget state so formElement() can access it.
820
    static::setWidgetState($this->fieldParents, $field_name, $form_state, $field_state);
821 822 823

    if ($max > 0) {
      for ($delta = 0; $delta < $max; $delta++) {
824

825 826 827 828 829
        // Add a new empty item if it doesn't exist yet at this delta.
        if (!isset($items[$delta])) {
          $items->appendItem();
        }

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
        // For multiple fields, title and description are handled by the wrapping
        // table.
        $element = array(
          '#title' => $is_multiple ? '' : $title,
          '#description' => $is_multiple ? '' : $description,
        );
        $element = $this->formSingleElement($items, $delta, $element, $form, $form_state);

        if ($element) {
          // Input field for the delta (drag-n-drop reordering).
          if ($is_multiple) {
            // We name the element '_weight' to avoid clashing with elements
            // defined by widget.
            $element['_weight'] = array(
              '#type' => 'weight',
845
              '#title' => $this->t('Weight for row @number', array('@number' => $delta + 1)),
846 847 848 849 850 851 852 853
              '#title_display' => 'invisible',
              // Note: this 'delta' is the FAPI #type 'weight' element's property.
              '#delta' => $max,
              '#default_value' => $items[$delta]->_weight ?: $delta,
              '#weight' => 100,
            );
          }

854 855 856
          // Access for the top element is set to FALSE only when the paragraph
          // was removed. A paragraphs that a user can not edit has access on
          // lower level.
857
          if (isset($element['#access']) && !$element['#access']) {
858
            $this->realItemCount--;
859 860 861 862
          }
          else {
            $elements[$delta] = $element;
          }
863 864
        }
      }
865
    }
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
866

867 868 869
    $field_state = static::getWidgetState($this->fieldParents, $field_name, $form_state);
    $field_state['real_item_count'] = $this->realItemCount;
    static::setWidgetState($this->fieldParents, $field_name, $form_state, $field_state);
870

871 872 873 874 875 876 877 878
    $elements += [
      '#element_validate' => [[$this, 'multipleElementValidate']],
      '#required' => $this->fieldDefinition->isRequired(),
      '#field_name' => $field_name,
      '#cardinality' => $cardinality,
      '#max_delta' => $max - 1,
    ];

879
    if ($this->realItemCount > 0) {
880 881
      $elements += array(
        '#theme' => 'field_multiple_value_form',
Jeroen's avatar
Jeroen committed
882
        '#cardinality_multiple' => $is_multiple,
883 884 885
        '#title' => $title,
        '#description' => $description,
      );
886 887
    }
    else {
888
      $classes = $this->fieldDefinition->isRequired() ? ['form-required'] : [];
889
      $elements += [
890
        '#type' => 'container',
891
        '#theme_wrappers' => ['container'],
Jeroen's avatar
Jeroen committed
892
        '#cardinality_multiple' => TRUE,
893 894 895 896
        'title' => [
          '#type' => 'html_tag',
          '#tag' => 'strong',
          '#value' => $title,
897
          '#attributes' => ['class' => $classes],
898 899 900
        ],
        'text' => [
          '#type' => 'container',
901 902 903 904 905
          'value' => [
            '#markup' => $this->t('No @title added yet.', ['@title' => $this->getSetting('title')]),
            '#prefix' => '<em>',
            '#suffix' => '</em>',
          ]
906 907 908
        ],
      ];

909 910 911 912
      if ($this->fieldDefinition->isRequired()) {
        $elements['title']['#attributes']['class'][] = 'form-required';
      }

913 914 915 916 917 918 919
      if ($description) {
        $elements['description'] = [
          '#type' => 'container',
          'value' => ['#markup' => $description],
          '#attributes' => ['class' => ['description']],
        ];
      }
920
    }
921

922 923
    $host = $items->getEntity();
    $this->initIsTranslating($form_state, $host);
Jeroen's avatar
Jeroen committed
924

925 926
    if (($this->realItemCount < $cardinality || $cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) && !$form_state->isProgrammed() && !$this->isTranslating) {
      $elements['add_more'] = $this->buildAddActions();
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
927
    }
928

Jeroen's avatar
Jeroen committed
929 930
    $elements['#attached']['library'][] = 'paragraphs/drupal.paragraphs.admin';

931
    return $elements;
Jeroen Bobbeldijk's avatar
Jeroen Bobbeldijk committed
932 933
  }

934 935 936 937 938 939 940 941 942 943 944 945 946
  /**
   * {@inheritdoc}
   */
  public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
    $parents = $form['#parents'];

    // Identify the manage field settings default value form.
    if (in_array('default_value_input', $parents, TRUE)) {
      // Since the entity is not reusable neither cloneable, having a default
      // value is not supported.
      return ['#markup' => $this->t('No widget available for: %label.', ['%label' => $items->getFieldDefinition()->getLabel()])];
    }

947 948 949 950 951 952 953
    $elements = parent::form($items, $form, $form_state, $get_delta);

    // Signal to content_translation that this field should be treated as
    // multilingual and not be hidden, see
    // \Drupal\content_translation\ContentTranslationHandler::entityFormSharedElements().
    $elements['#multilingual'] = TRUE;