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.