Skip to content

Instantly share code, notes, and snippets.

@eevensen
Last active March 8, 2022 13:58
Show Gist options
  • Save eevensen/8f8dd47b0943f665c0368ed2e11b695d to your computer and use it in GitHub Desktop.
Save eevensen/8f8dd47b0943f665c0368ed2e11b695d to your computer and use it in GitHub Desktop.
How do I import multiple text values from a CSV and also set the text format? (Drupal 9 migrate). SEE CODE COMMENTS
title sentences random_data
A Sentence-A1|Sentence-A2|Sentence-A3 abc123
B Sentence-B1|Sentence-B2|Sentence-B3 def456
id: example
label: 'Example'
source:
plugin: 'csv'
delimiter: ','
enclosure: '"'
path: 'data.csv'
header_offset: 0
ids:
- title
fields:
0:
name: id
label: id
1:
name: sentences
label: sentences
2:
name: random_data
label: random_data
process:
type:
plugin: default_value
default_value: article
title: title
uid:
plugin: default_value
default_value: 1
# This is how I would import a single value with the text format:
field_random_data/value: random_value
field_random_data/format:
plugin: default_value
default_value: 'basic_html'
# How do I import multiple values separated by a delimiter '|' and also set the text format?
# I am aware that sub_process does not work with scalar values, ref: https://www.drupal.org/project/drupal/issues/3175508
# So the code below does not work. Any suggestions?
# Could I use the new process plugin for 'MultipleValues', if yes, how?
# https://git.drupalcode.org/project/migrate_plus/blob/HEAD/src/Plugin/migrate/process/MultipleValues.php
field_sentences:
-
plugin: explode
delimiter: '|'
source: sentences
-
plugin: sub_process
process:
value: '0'
format:
plugin: default_value
default_value: 'basic_html' # How can I set the text format after I have exploded the text string to an array?
destination:
plugin: 'entity:node'
default_bundle: article
@heddn
Copy link

heddn commented Mar 8, 2022

The easiest way is to build a custom process plugin that returns the expected values. Something like this (untested).

function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $exploded = explode('|', $value);
    return array_map(static function ($exploded_value) {
      return ['value' => $exploded_value, 'text_format' => 'basic_html'];
    }, $exploded);
}

migration.yml

field_sentences: 
  plugin: my_custom_process_plugin
  source: sentences

@eevensen
Copy link
Author

eevensen commented Mar 8, 2022

The easiest way is to build a custom process plugin that returns the expected values. Something like this (untested).

Okay, I understand. Sounds good. I was hoping there would be a contrib process plugin for this already ;)
Thank you for your help, @heddn !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment