我们创建了一个名为paragraphs_clean 的模块,它实现了hook_entity_update()(注意:模块名称必须与entity_update() 挂钩函数的前缀相同)获得灵感从这里:https://www.drupal.org/project/paragraphs/issues/2741937#comment-13181377。
如前所述,即使有修订和翻译,它似乎也能很好地工作。此外,我们还必须调整原始 php 代码以在段落也有段落(即嵌套段落)的情况下运行。
这段代码比上面的更高效,因为它只会从上下文中加载实体的孤立段落。
代码如下:
<?php
/**
* @file
* Paragraphs clean module.
*/
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\field\Entity\FieldConfig;
/**
* Implements hook_entity_update().
*
* When form updates, delete any paragraph entities that were removed.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
*/
function paragraphs_clean_entity_update(EntityInterface $entity) {
// Only act on content entities.
if (!($entity instanceof FieldableEntityInterface)) {
return;
}
$fieldManager = \Drupal::service('entity_field.manager');
$parentEntities = $fieldManager->getFieldMapByFieldType('entity_reference_revisions');
if (!array_key_exists($entity->getEntityTypeId(), $parentEntities)) {
return;
}
$paragraph_definitions = [];
// loop through all paragraph types
foreach ($parentEntities[$entity->getEntityTypeId()] as $field_id => $settings) {
if ($configField = FieldConfig::loadByName($entity->getEntityTypeId(), $entity->bundle(), $field_id)) {
$paragraph_definitions[] = $configField;
}
}
if (empty($paragraph_definitions)) {
return;
}
foreach ($paragraph_definitions as $paragraph_definition) {
//get entity type name to make it work with any kind of parent entity (node, paragraph, etc.)
$entityTypeName = $entity->getEntityTypeId();
// Remove orphaned paragraphs.
$query = \Drupal::database()->select('paragraphs_item_field_data', 'pfd')
->fields('pfd', ['id'])
->condition('pfd.parent_type', $entityTypeName)
->condition('pfd.parent_id', $entity->id())
->condition('pfd.parent_field_name', $paragraph_definition->getName());
$query->addJoin('left', $entityTypeName.'__'.$paragraph_definition->getName(),'nt','pfd.id=nt.'.$paragraph_definition->getName().'_target_id');
$query->isNull('nt.'.$paragraph_definition->getName().'_target_id');
$query->distinct();
$paragraph_ids = $query->execute()->fetchCol();
if ($paragraph_ids) {
$para_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
foreach ($paragraph_ids as $paragraph_id) {
if ($para = $para_storage->load($paragraph_id)) {
$para->delete();
drupal_set_message(t('Paragraph of type "%type" has been deleted: %id', ['%id' => $paragraph_id, '%type' => $paragraph_definition->getName()]));
}
}
}
}
}