Импорт данных Json в узел


Моя цель - импортировать свой собственный набор данных в Drupal 8 с помощью модулей миграции (migrate_plus, migrate_tools).

В Drupal я использую модуль Paragraph, и здесь начинаются мои проблемы. Я создал свой собственный плагин для преобразования собственных данных в абзац. Преобразованные данные хороши, если я создам новый узел и присоединю его к функции transform(), но это не то, что я хочу, это только для того, чтобы сказать, что мои данные могут быть правильными (см. Комментарии ниже)

Я делаю импорт с помощью базовое поле, такое как текст, теги или файл, и при этом будет сгенерирован узел, но я не могу понять, почему "возврат $абзацев" ничего не даст.

PS: Я размонтирую/устанавливаю свой модуль (и созданный conf migrate_plus) каждый раз, когда я изменяю свой .yml файл и перестраиваю кэш.

  • Друпал (8.1.1)
    • миграция_плюс (8.x-2.x-dev)
    • миграционные инструменты (8.x-2.0-бета1)
    • миграция_ресурс_json (8.x-2.x-dev)
    • пункты (8.x-1.0-rc4)

Конфигурация миграции для статей (config/install/migrate_plus.migration.article.yml)

id: article
label: Article
migration_group: Articles
migration_dependencies: {}

source:
  plugin: json_source
  path: http://www.example.com/dataset.json
  headers:
    Accept: 'application/json'
  identifier: id
  identifierDepth: 0
  fields:
    - id
    - title
    - paragraphs

destination:
  plugin: entity:node

process:
  type:
    plugin: default_value
    default_value: article

  title: title
  
  field_paragraphes: 
      - source: paragraphs
        plugin: paragraphs_import

  uid:
    plugin: default_value
    default_value: 0

Пример набора данных:

[{
    "id": "1",
    "title": "article 1",
    "paragraphs": [{
        "id": "1",
        "title": "paragraph 1 article 1"
    }, {
        "id": "2",
        "title": "paragraph 2 article 1"
    }]
}, {
    "id": "2",
    "title": "article 2",
    "paragraphs": [{
        "id": "3",
        "title": "paragraph 1 article 2"
    }, {
        "id": "4",
        "title": "paragraph 2 article 2"
    }]
}]

Пользовательский плагин, используемый в "field_paragraphes" (/src/Plugin/migrate/process/ParagraphsImport.php)

<?php

/**
 * @file
 * Contains \Drupal\my_module\Plugin\migrate\process\ParagraphsImport.
 */

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

/**
 *
 * @MigrateProcessPlugin(
 *   id = "paragraphs_import"
 * )
 */
class ParagraphsImport extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    // code only to add 1 paragraph to my node, to make thing easier to start

    // paragraph_txtimg = one paragraph type allowed into my paragraph field

    $paragraphs=array();
    $ppt_values = array(
      'id' => NULL,
      'type' => 'paragraph_txtimg',
    );
    $ppt_paragraph = Paragraph::create($ppt_values);
    $ppt_paragraph->save();


    
    // IF I uncomment this part, it will create a new node with a paragrah, this works
    // But this is not what I want to do, I want to return the paragraph to the node that will be created by migrate
    /*
      $node = Node::create(array(
        'type' => 'article',
        'title' => 'This is a new article with a fresh paragraph generated !',
        'field_paragraphes' => array(
          array(
            'target_id' => $ppt_paragraph->id(),
            'target_revision_id' => $ppt_paragraph->getRevisionId(),
          ),
        ),
      ));
      $node->save();
    */

    $target_id_dest = $ppt_paragraph->Id();
    $target_revision_id_dest = $ppt_paragraph->getRevisionId();
    $paragraphs[] = array('target_id' => $target_id_dest, 'target_revision_id' => $target_revision_id_dest);

    return $paragraphs;
  }

}
Author: leymannx, 2016-05-27

1 answers

Я наконец-то нашел пропавший ключ :
преобразование() вызывается для КАЖДОГО элемента источника.

field_paragraphes: 
 - source: paragraphs
   plugin: paragraphs_import # will be called for each value of source: paragraphs

И поэтому возвращаемое значение должно быть определением редакции абзаца:

<?php

/**
 * @file
 * Contains \Drupal\my_module\Plugin\migrate\process\ParagraphsImport.
 */

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

/**
 *
 * @MigrateProcessPlugin(
 *   id = "paragraphs_import"
 * )
 */
class ParagraphsImport extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    // transform() is called on each source value

    $paragraph_options = array(
      'id' => NULL,
      'type' => 'paragraph_txtimg',
    );
    $paragraph = Paragraph::create($paragraph_options);
    $paragraph->save();

    return $paragraph;
  }

}
 2
Author: benj, 2016-05-31 14:52:53