Skip to content

Instantly share code, notes, and snippets.

@purplexa
Created February 21, 2014 04:50
Show Gist options
  • Save purplexa/9128965 to your computer and use it in GitHub Desktop.
Save purplexa/9128965 to your computer and use it in GitHub Desktop.
Reversing an EntityReference direction in Drupal Migrate
<?php
/**
* This is the content type which should have the EntityReference field in the new site.
*/
class MainContentTypeMigration extends DrupalNode6Migration {
public function __construct(array $arguments) {
parent::__contstruct($arguments);
$this->addFieldMapping('my_new_field', 'my_old_field');
// This is how you normally handle a NodeReference migration.
$this->addFieldMapping('normal_entityreference', 'normal_nodereference')
->sourceMigration(array('ExampleUnrelated'));
}
}
/**
* This is an unrelated content type used for the 'ExampleUnrelated' migration as an example of a normal NodeReference migration.
*/
class ExampleUnrelatedMigration extends DrupalNode6Migration {
public function __construct(array $arguments) {
$this->addFieldMapping('unrelated_new_field', 'unrelated_old_field');
}
}
/**
* This is the content type which had the NodeReference field in the old site.
*/
class ReferencedContentTypeMigration extends DrupalNode6Migration {
public function __construct($arguments) {
parent::__construct($arguments);
$this->addFieldMapping('my_random_new_field', 'my_random_old_field');
}
// Here's where the magic sauce happens. This method is run after the content type is imported into the new site.
// We have to do the reversal here since we can't make an EntityReference unless the referenced entity exists.
public function complete($entity, stdClass $row) {
// Instead of calling the sourceMigration() method above, we have to manually invoke handleSourceMigration() in order to
// get the node id for the node referenced on the old content type.
$main_content_type_id = parent::handleSourceMigration('MainContent', $row->field_backward_nodereference);
// Once we have the id for the node we want to have the reference, we can add the reference and save the node.
$main_content = node_load($main_content_type_id);
if (isset($main_content->nid)) {
$main_content->field_fixed_nodereference[$main_content->language][] = array(
'target_id' => $entity->vid,
);
node_save($main_content);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment