0

I've a user migration class as shown here.

However for some reason users are created with empty required fields (such as e-mail).

How do I implement custom validation of the field during migration?

So I can fail the validation for specific row and continue the migration? So the specific rows won't be migrated and they will appear in the list of the one which has error in it.

Is there any method for that?

2

You can accomplish this using the ::prepareRow() method on your migration class. You'll have access to the source field values in the $row variable. This method is called once for each record being imported, and returning FALSE will skip the row in question.

Example:

function prepareRow($row) {
  if (!validate_my_field($row->my_custom_field)) {
    return FALSE;
  }
}

More info https://www.drupal.org/node/1132582

For Drupal 8 you could accomplish the same by either implementing a custom source plugin with a prepareRow() method. Or by implementing hook_migrate_prepare_row() and performing your validation there.

| improve this answer | |
0

Here is another example of row validation using prepareRow() method (using CSV import):

  /**
   * Modifies the row to be imported.
   *
   * @inheritdoc
   */
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }

    // Loop through all the columns in this row and do some validation.
    $error_messages = '';
    foreach ($row as $column_key => $column_value) {
      if ($column_key == 'csvrownum') {
        continue;
      }

      // Validate email address.
      if ($column_key == 'Email' && !valid_email_address($column_value)) {
        $error_messages .= t('Invalid email address. ');
      }

      // Check for character limits.
      if ($column_key != 'Contact preference' && _engage_migrate_character_limit_exceeded($column_key, $column_value)) {
        $error_messages .= t('@column_key is too long. ', array('@column_key' => $column_key));
      }

      // Check for mandatory columns.
      $mandatory_columns = array('Firstname', 'Lastname', 'Email');
      if (empty($column_value) && in_array($column_key, $mandatory_columns)) {
        $error_messages .= t('@column_key can not be empty. ', array('@column_key' => $column_key));
      }
    }

    // Save the messages for this row.
    if (!empty($error_messages)) {
      $this->queueMessage($error_messages);
      return FALSE;
    }

    // All good, import the row.
    return TRUE;
  }

So basically in order to fail the field validation, you should return FALSE for prepareRow() and optionally queue the error message using queueMessage() method.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.