Preserving Role ID (rid) in a Drupal 6 to Drupal 7 Role Migration

Profile picture for user Phil Frilling
By Phil Frilling, 23 March, 2016
I was working on setting up a role migration from Drupal 6 to Drupal 7. After some time, I noticed that the role id's were not being preserved, which was going to cause a problem for me when I went to take the migration to the live server. I initially tried using the addFieldMapping function to link the source rid to the destination rid (similar to preserving the nid for nodes or the uid for users). However, this failed to save any of the roles during migration. In the end, I used the complete() function of a custom class to manually update the role table to assign the source ID to the destination's role table. The whole class is below:

/**
 * Class to extend the role migration.
 */
class MyRoleMigration extends DrupalRole6Migration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);   
     // This option does not work
     // $this->addFieldMapping('rid', 'rid')->description(t('Preserve the D6 RID')); 
     // Set the is_new to force the RID to remain.
     // $this->addFieldMapping('is_new')->defaultValue(1);
  }
  
  public function complete($entity, $row) {
    // Update the saved rid to the original rid from D6.
    $num_updated = db_update('role')
      ->fields(array(
        'rid' => $row->rid,
      ))
      ->condition('rid', $entity->rid, '=')
      ->execute();
    if ($num_updated) {
      // If the role table was updated, change the entity->rid to the source
      // so the rollback options works properly.
      $entity->rid = $row->rid; 
    }
  }
}