Field handlers

Field handlers work much like destination handlers, except rather than prepare() and complete() being called once per node or user, they are called once per field of the registered type. For example, if you have two text fields, field_description and field_annotation, on a given node type, when migrating a node of that type MigrateTextFieldHandler will be invoked twice - once for each field. They also have prepare() and complete() methods, which are actually invoked from destination handler MigrateFieldsEntityHandler's prepare() and complete() methods. The signatures are a bit different, though:

public function prepare($entity, array $field_info, array $instance, array $values);

public function complete($entity, array $field_info, array $instance, array $values);

The complete entity object (as it exists at this point in the prepare or complete stage) is passed first, followed by field info and field instance arrays describing how the field is set up (the former applies to all instances of the field, the latter to the instance on this particular entity type). Finally, the values to be assigned to the field are passed. The job of the field handler is to translate this array of simple raw values, and convert it into the array form expected by Drupal 7 core or Drupal 6 CCK.

As an example, let's consider the most basic field handler, MigrateValueFieldHandler (Drupal 7 version):

class MigrateValueFieldHandler extends MigrateFieldHandler {
  public function __construct() {
    // This handler will take care of all the simple core field types
    $this->registerTypes(array('value', 'list', 'list_boolean', 'list_integer',
      'list_float', 'list_text', 'number_integer', 'number_decimal', 'number_float'));
  }

  // Here, we take a simple array of values (for an integer field, it might look like
  // array(35, -23, 85738)
  public function prepare($entity, array $field_info, array $instance, array $values) {
    $migration = Migration::currentMigration();
    $arguments = (isset($values['arguments']))? $values['arguments']: array();
    // In Drupal 7, field values are indexed by language, which can be specified
    // at various levels - this member implemented in MigrateFieldHandler works
    // out which language to use, applying appropriate defaults
    $language = $this->getFieldLanguage($entity, $field_info, $arguments);
    // Setup the standard Field API array for saving.
    $delta = 0;
    foreach ($values as $value) {
      $return[$language][$delta]['value'] = $value;
      $delta++;
    }
    if (!isset($return)) {
      $return = NULL;
    }
    return $return;
  }
}