我有一个带有多值分类法参考字段(field_article_countries)的文章内容类型,用于国家词汇。对于相同的词汇表,我还有一个具有多值分类法参考字段(field_book_countries)的图书内容类型。
我试图:
例如,图书节点(ID 12)将field_book_countries设置为none。一个项目节点(ID 3)将field_article_countries设置为意大利;另一个项目节点(ID 40)将field_article_countries设置为希腊、土耳其、埃及、巴西、西班牙。
我想:
我用来实现这一点的代码如下。
$articleIDs = [
'3',
'40'
];
// Load all the articles.
$articles = \Drupal\node\Entity\Node::loadMultiple($articleIDs);
// Loop through the loaded articles.
foreach ($articles as $article) {
// Get the "Countries" Values.
$countries = $article->get('field_article_countries')->getValue();
// Set the 'countries' values to the node "book".
$book->set('field_book_countries', $countries);
// $book->field_book_countries[] = ['target_id' => $countries];
}
// Save the Book node.
$book-->save();但是,由于某些原因和在循环期间,field_book_countries的新值正在覆盖现有的值。
我做错了什么?
发布于 2020-05-17 01:27:54
您需要循环遍历所有文章,将所有国家保存在一个临时数组中。循环完成后,保存图书节点中的国家。
例如:
$countries = [];
// Loop through loaded articles.
foreach ($articles as $article) {
// Get the "Countries" Values.
$countries = array_merge($countries, $article->get('field_article_countries')->getValue());
}
// Set the 'countries' values to the node "book".
$book->set('field_book_countries', $countries);
// Save Book node.
$book-->save();https://drupal.stackexchange.com/questions/293759
复制相似问题