You are here

protected function LayoutParagraphsLayout::insertSiblingComponent in Layout Paragraphs 2.0.x

Insert an new item adjacent to $sibling.

Parameters

string $sibling_uuid: The existing sibling paragraph component's uuid.

\Drupal\paragraphs\Entity\Paragraph $new_paragraph: The paragraph component to add.

int $delta_offset: Where to add the new item in relation to sibling.

Return value

$this

2 calls to LayoutParagraphsLayout::insertSiblingComponent()
LayoutParagraphsLayout::insertAfterComponent in src/LayoutParagraphsLayout.php
Insert a paragraph component after an existing component.
LayoutParagraphsLayout::insertBeforeComponent in src/LayoutParagraphsLayout.php
Insert a paragraph component before an existing component.

File

src/LayoutParagraphsLayout.php, line 409

Class

LayoutParagraphsLayout
Provides a domain object for a complete Layout Paragraphs Layout.

Namespace

Drupal\layout_paragraphs

Code

protected function insertSiblingComponent(string $sibling_uuid, Paragraph $new_paragraph, int $delta_offset = 0) {

  // Create a layout component for the new paragraph.
  $new_component = $this
    ->getComponent($new_paragraph);

  // Find the existing sibling component, and copy the layout settings
  // into the new component to be inserted.
  if ($existing_component = $this
    ->getComponentByUuid($sibling_uuid)) {

    // Copy layout settings into the new component.
    $sibling_settings = $existing_component
      ->getSettings();
    $new_component_settings = [
      'parent_uuid' => $sibling_settings['parent_uuid'] ?? NULL,
      'region' => $sibling_settings['region'] ?? NULL,
    ];
    $new_component
      ->setSettings($new_component_settings);

    // Get the paragraph entity from the component.
    $new_paragraph = $new_component
      ->getEntity();
    $new_paragraph
      ->setParentEntity($this
      ->getEntity(), $this
      ->getFieldName());

    // Splice the new paragraph into the field item list.
    $list = $this->paragraphsReferenceField
      ->getValue();
    $delta = $this
      ->getComponentDeltaByUuid($sibling_uuid);
    $delta += $delta_offset;
    array_splice($list, $delta, 0, [
      'entity' => $new_paragraph,
    ]);
    $this->paragraphsReferenceField
      ->setValue($list);
  }
  else {

    // @todo: throw exception.
  }
  return $this;
}