You are here

paragraphs_edit.module in Paragraphs Edit 8

Same filename and directory in other branches
  1. 8.2 paragraphs_edit.module

Allows users to edit/clone and delete paragraphs.

File

paragraphs_edit.module
View source
<?php

/**
 * @file
 * Allows users to edit/clone and delete paragraphs.
 */
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\paragraphs_edit\ParagraphCloneForm;
use Drupal\paragraphs_edit\ParagraphDeleteForm;
use Drupal\paragraphs_edit\ParagraphEditForm;

/**
 * Implements hook_entity_type_build().
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
 */
function paragraphs_edit_entity_type_build(array &$entity_types) {
  $entity_types['paragraph']
    ->setFormClass('node_edit', ParagraphEditForm::class);
  $entity_types['paragraph']
    ->setFormClass('node_clone', ParagraphCloneForm::class);
  $entity_types['paragraph']
    ->setFormClass('node_delete', ParagraphDeleteForm::class);
}

/**
 * @param $variables
 *
 * @see template_preprocess_field()
 */
function paragraphs_edit_preprocess_field(&$variables) {
  if (empty($variables['field_type']) || $variables['field_type'] !== 'entity_reference_revisions') {
    return;
  }
  $element = $variables['element'];
  if ($element['#entity_type'] !== 'node') {
    return;
  }

  /** @var \Drupal\node\NodeInterface $parent */
  $parent = $element['#object'];

  /** @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsFieldItemList $field */
  $field = $element['#items'];
  $field_definition = $field
    ->getFieldDefinition();
  $field_storage_definition = $field_definition
    ->getFieldStorageDefinition();
  if ($field_storage_definition
    ->getSetting('target_type') !== 'paragraph') {
    return;
  }
  $delta = 0;
  while (!empty($element[$delta])) {

    /** @var \Drupal\paragraphs\ParagraphInterface $entity */
    $entity = $field
      ->get($delta)->entity;
    BubbleableMetadata::createFromObject($parent)
      ->applyTo($variables['items'][$delta]['content']);
    $variables['items'][$delta]['content']['#contextual_links']['paragraph'] = [
      'route_parameters' => [
        'node' => $parent
          ->id(),
        'field' => $variables['field_name'],
        'delta' => $delta,
        'paragraph' => $entity
          ->id(),
      ],
      'metadata' => [
        'changed' => $parent
          ->getChangedTime(),
      ],
    ];
    $delta++;
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function paragraphs_edit_preprocess_paragraph(&$variables) {
  if (isset($variables['title_suffix']['contextual_links'])) {
    $variables['content']['contextual_links'] = $variables['title_suffix']['contextual_links'];
    $variables['content']['contextual_links']['#weight'] = -100;
  }
}