首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将图像从图像字段移动到另一个字段

将图像从图像字段移动到另一个字段
EN

Drupal用户
提问于 2021-01-28 08:23:42
回答 1查看 342关注 0票数 1

几个月前,我为一个客户开发了一个基于D8的网站,其图像字段具有多个值,显示为基础图片库

现在,我的客户改变了主意,所以现在他想要设置插入图像或视频的可能性,所以我决定使用段落来让他选择是图像还是嵌入视频

问题是客户有超过1000个节点,每个节点平均有3-4个图像,所以如果我将字段更改为第一段,以前保存在Image字段中的图像不会移动到段落字段。

是否有将图像从图像字段“迁移”到段落引用图像字段的方法?

如你所知,重新上传图片可能是,如果我可以说,是一个皮塔。

EN

回答 1

Drupal用户

回答已采纳

发布于 2021-01-28 11:34:32

欢迎来到这里,MineDoodler!

不久前,我发现了同样的问题,所以我开发了这段代码。(请注意,我刚刚从开发开始,可以更容易地实现这一点)。

阅读注释以理解代码。

代码语言:javascript
复制
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号开始的,是由我的知识发展而来的。

我忘记提到这段代码是在开发PHP中,在展开模块中执行的。

票数 0
EN
页面原文内容由Drupal提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://drupal.stackexchange.com/questions/299789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档