我正在试图找到站点中的所有绝对url (在wysiwyg内容、url字段、config中),以便稍后通过手动管理将它们转换为相对url。所有涉及的URL都在同一个Drupal站点中。我成功地使用PHPMyAdmin查找并记录了包含绝对urls (节点- /node/NID/edit、菜单项- /admin/structure/menu/item/MLID/edit等)的容易访问的实体。然而,我在段落方面遇到了困难。
如何解决这个问题呢?如何找到包含绝对链接的段落的主机节点?
发布于 2018-09-14 20:46:56
为此使用API可能比使用SQL要容易一些。我会尝试加载所有节点,循环遍历它们的所有字段,并以这种方式检查值。如果您点击了段落字段,请恢复并检查其字段。
这是一个非常粗略的示例函数,但是它应该会让您:
function entityHasFieldWithAbsUrl(\Drupal\Core\Entity\ContentEntityInterface $entity, array $types) {
foreach ($entity->getFields() as $key => $field) {
$field_type = $field->getFieldDefinition()->getType();
$field_settings = $field->getSettings();
if ($field_type == 'entity_reference_revisions' && $field_settings['target_type'] == 'paragraph') {
foreach ($field as $item) {
if ($item->entity instanceof \Drupal\paragraphs\ParagraphInterface) {
if (entityHasFieldWithAbsUrl($item->entity, $types)) {
return TRUE;
}
}
}
}
elseif (in_array($field_type, $types)) {
foreach ($field as $item) {
// Change this to something better...
if (strpos($item->value, 'https://www.example.com/') !== FALSE) {
return TRUE;
}
}
}
}
return FALSE;
}你会用这样的方法:
$nodes_with_abs_urls = [];
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple();
$types = ['text', 'text_long', 'text_with_summary', 'string'];
foreach ($nodes as $node) {
if (entityHasFieldWithAbsUrl($node, $types)) {
$nodes_with_abs_urls[] = $node->id();
}
}您可能需要调整类型,以适应您的安装,但它应该在一个基本水平上工作。
发布于 2018-09-17 14:19:00
因此,我最终做的是搜索PHPMyAdmin中的URL,选择属于段落字段的所有表(它们是前缀paragraph__),并收集它们的所有entity_ids。然后使用临时Drush命令加载所有这些段落,并对每个段落递归加载$paragraph->getParentEntity(),直到它到达所需的实体类型(在本例中为节点)。然后我记录了节点ids。
function mymodule_drush_command() {
$items = [];
$items['mycommand'] = [
'description' => 'Find the nids of the pids',
'arguments' => [],
'drupal dependencies' => ['mymodule'],
'aliases' => [],
];
return $items;
}
function drush_mymodule_mycommand() {
// Could be improved by retrieving ids via query.
$pids = [/* paragraph entity_ids */];
// For each, recursively search ancestors.
$nids = array_unique(array_filter(array_map(function($pid) {
return _mymodule_find_node(\Drupal\paragraphs\Entity\Paragraph::load($pid));
}, $pids)));
// Print results
drush_print_r(array_map(function($nid) {
return '/node/' . $nid . '/edit';
}, $nids));
}
function _mymodule_find_node($entity){
// Could be improved by handling more than just nodes
if ($entity instanceof \Drupal\node\NodeInterface) return $entity->id();
// If still a paragraph, climb
if ($entity instanceof \Drupal\paragraphs\ParagraphInterface) return _mymodule_find_node($entity->getParentEntity());
// Otherwise, this is an entity we didn't want.
return null;
}这个操作的大部分可以是自动化的。它可以通过查询(而不是PHPMyAdmin )获取实体ids,并处理不同的根类型,如块、术语等,还可以通过不加载每个段落来提高性能。但是上面的这些做了我现在所需要的,所以我就这样离开了它。
https://drupal.stackexchange.com/questions/269353
复制相似问题