Shomeya

Two web artists. One amazing company.

Update allowed values during a content migration

from Michael Prasuhn on May 28, 2012 05:00pm

Many times during a large data migration we have a case where we want to import some data into field that should be a list type with a select widget (either dropdown or multi-select) but we don't know what all those values are when setting up the field type, or starting development since the data to be migrated is still being edited.

In these cases what we end up doing is just making sure that each imported value is added to the allowed values list for that field if it isn't already present. To do that we use the following pattern.

In a custom module add the following bit of code:

<?php
/**
* Verify that a given value is in the list of allowed values for a field.
*/
function _MYMODULE_verify_allowed_value($field_name, $value, $key = NULL) {
  $field_info = field_info_field($field_name);
  if ($field_info) {
    if ($key == NULL) {
      $key = $value;
    }
    if (array_key_exists($key, $field_info['settings']['allowed_values'])) {
      return TRUE;
    }
    else {
      $field_info['settings']['allowed_values'][$key] = $value;
      try {
        field_update_field($field_info);
      }
      catch (FieldException $e) {
        return FALSE;
      }
      return TRUE;
    }
  }
}

Then in your migration simply call that function from prepareRow():

<?php
class MymoduleCustomMigration extends MymoduleBaseMigration {
  public function __construct() {
    /** snip */
  }

  /**
* PrepareRow callback.
*/
  public function prepareRow(stdClass $row) {
    _MYMODULE_verify_allowed_value('field_product_color', $row->color);
    _MYMODULE_verify_allowed_value('field_product_sizes', $row->size);
  }
}

What this does is call this function for each row of data to be migrated and ensure that it's value is present or added to the allowed values list before the new item is actually saved.

blog comments powered by Disqus