Migrating a Drupal 7 User Profile2 Image Field to a Drupal 8 User Image Field
Consider this scenario:
- Drupal 7 site contains Profile2 profile called person with image field called field_oldsite_person_image.
- Users each have a profile2 profile associated with their account.
- Drupal 8 site has an image field called field_newsite_user_photo on the user entity itself.
If you need to migrate the image field from the Drupal 7 profile to the Drupal 8 user entity you can extend the d7_user plugin and query for the additional field data. I’m executing an extra query for each user (because the code is in the prepareRow() method), rather than attempting to pull all of the profile data as part of the query in the query() method of the class.
First, create a file in your module like /modules/custom/mysite_migrate/src/Plugin/migrate/source/MysiteUser.php that extends the d7_user plugin:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<?php namespace Drupal\mysite_migrate\Plugin\migrate\source; use Drupal\migrate\Row; use Drupal\user\Plugin\migrate\source\d7\User as d7_user; /** * User entities from the d7 database. * * @MigrateSource( * id = "mysite_user", * source_module = "user" * ) */ class MysiteUser extends d7_user { /** * {@inheritdoc} */ public function prepareRow(Row $row) { $uid = $row->getSourceProperty('uid'); $fields = $this->getPersonProfileFields($uid); if (!empty($fields)) { foreach ($fields as $data_row) { foreach ($data_row as $field => $value) { $row->setSourceProperty($field, $value); } } } return parent::prepareRow($row); } /** * Returns an already-executed Drupal query containing person profile fields. * * @param int $uid * User ID. * * @return \Drupal\Core\Database\StatementInterface|null * Already-executed database query object. */ private function getPersonProfileFields($uid) { $query = $this->select('users', 'u'); $query->condition('u.uid', $uid); $query->condition('p.type', 'person'); $query->leftJoin('profile', 'p', 'p.uid = u.uid'); $query->leftJoin('field_data_field_oldsite_person_image', 'image', 'image.entity_id = p.pid'); $query->fields('image', [ 'field_oldsite_person_image_fid', 'field_oldsite_person_image_alt', 'field_oldsite_person_image_title', ]); return $query->execute(); } } |
The site I’m working on that lead to this code utilizes several profiles, hence the getPersonProfileFields() method (there are other methods for other profile types).
Next, use the mysite_user source plugin instead of d7_user.
1 2 |
source: plugin: mysite_user |
Finally, you can map the values to the Drupal 8 image field:
1 2 3 4 5 6 7 |
field_newsite_user_photo/target_id: plugin: migration_lookup migration: grin_files source: field_oldsite_person_image_fid no_stub: true field_newsite_user_photo/alt: field_oldsite_person_image_alt field_newsite_user_photo/title: field_oldsite_person_image_title |