发布于 2021-01-28 11:34:32
欢迎来到这里,MineDoodler!
不久前,我发现了同样的问题,所以我开发了这段代码。(请注意,我刚刚从开发开始,可以更容易地实现这一点)。
阅读注释以理解代码。
use \Drupal\node\Entity\Node;
use \Drupal\paragraphs\Entity\Paragraph;
use \Drupal\file\Entity\File;
function migrateImages() {
// Get all products
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'productos');
$nids = $query->execute();
$allNids = [];
// In my case, i had a keyed array (First element was [213] => "157") so I turned into ([0] => "157")
foreach ($nids as $nid) {
$allNids[] = $nid;
}
// Go through every node
for ($i = 0; $i < count($nids); $i++) {
$nodeID = $allNids[$i];
// Load node.
$node = Node::load($nodeID);
// Get current paragraphs (if already has any).
$current = $node->get('field_prod_media')->getValue();
// Go through every image this node has.
foreach ($node->field_prod_img as $item) {
// Create new paragraph
$paragraph = Paragraph::create(['type' => 'YOUR_PARAGRAPH_TYPE']);
// Load image
$file = File::load($item->target_id);
// Save image
$paragraph->set('IMAGE_FIELD_IN_PARAGRAPH', $file);
// Force the new "alt". I've done this because it wasn't saving the alt.
$paragraph->field_img->alt = $item->alt;
// Check if it's new and save it.
$paragraph->isNew();
$paragraph->save();
// Add to the current paragraphs the new one.
$current[] = array(
'target_id' => $paragraph->id(),
'target_revision_id' => $paragraph->getRevisionId(),
);
}
// Set again all paragraphs, with the new ones.
$node->set('field_prod_media', $current);
$node->save();
dpm("node ".$node->label()." has been saved!");
}
}这个想法是从这个职位的7号开始的,是由我的知识发展而来的。
https://drupal.stackexchange.com/questions/299789
复制相似问题