function layout_paragraphs_paragraph_presave in Layout Paragraphs 1.0.x
Same name and namespace in other branches
- 2.0.x layout_paragraphs.module \layout_paragraphs_paragraph_presave()
Implements hook_ENTITY_presave().
Updates references to parent layout section uuids in cases where paragraphs are duplicated, for example when using the Replicate module.
@todo Consider changing approach if this issue is addressed in core: https://www.drupal.org/project/drupal/issues/3040556 (It is not possible to react to an entity being duplicated)
File
- ./
layout_paragraphs.module, line 94 - Contains layout_paragraphs.module.
Code
function layout_paragraphs_paragraph_presave(Paragraph $paragraph) {
$behavior_settings = $paragraph
->getAllBehaviorSettings();
$layout_paragraphs_settings = $behavior_settings['layout_paragraphs'] ?? [];
if (!empty($layout_paragraphs_settings['parent_uuid']) && ($parent = $paragraph
->getParentEntity())) {
$parent_field = $paragraph
->get('parent_field_name');
$field_name = $parent_field
->first()
->getString();
$item_list = $parent
->get($field_name);
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $item_list */
$sibling_paragraphs = $item_list
->referencedEntities();
if (count($sibling_paragraphs)) {
$uuid_map = [];
foreach ($sibling_paragraphs as $delta => $item) {
$uuid_map[$item
->uuid()] = $delta;
}
$parent_delta = $uuid_map[$layout_paragraphs_settings['parent_uuid']] ?? NULL;
// If the parent layout section is correctly referenced via
// parent_uuid, save the parent delta so we can correctly map
// uuids using the delta if content is duplicated.
if (isset($parent_delta)) {
$layout_paragraphs_settings['parent_delta'] = $parent_delta;
}
elseif (isset($layout_paragraphs_settings['parent_delta'], $sibling_paragraphs[$layout_paragraphs_settings['parent_delta']])) {
$updated_parent_uuid = $sibling_paragraphs[$layout_paragraphs_settings['parent_delta']]
->uuid();
$layout_paragraphs_settings['parent_uuid'] = $updated_parent_uuid;
}
// Since paragraph::preSave() has already been called,
// we have to set the serialized behavior settings directly
// rather than using setBehaviorSettings().
$behavior_settings['layout_paragraphs'] = $layout_paragraphs_settings;
$paragraph
->set('behavior_settings', serialize($behavior_settings));
}
}
}