public addError ( string $messageCode, string | array $field = '*', integer | array $options = [] ) : |
||
$messageCode | string | The message translation code. If you add a message that starts with "@" then no translation will take place. |
$field | string | array | The name of the field to add or an array of fields if the error applies to more than one field. |
$options | integer | array | An array of additional information to add to the error entry or a numeric error code. |
return | Returns $this for fluent calls. |
public function addError($messageCode, $field = '*', $options = [])
{
$error = [];
if (substr($messageCode, 0, 1) === '@') {
$error['message'] = substr($messageCode, 1);
} else {
$error['code'] = $messageCode;
}
if (is_array($field)) {
$fieldname = self::arraySelect(['path', 'name'], $field);
if ($fieldname) {
// This is a full field object.
$fieldKey = $fieldname;
$error['field'] = $fieldKey;
} else {
$fieldKey = '*';
$error['field'] = $field;
}
} else {
$fieldKey = $field;
if ($field !== '*') {
$error['field'] = $field;
}
}
if (is_array($options)) {
$error += $options;
} else {
if (is_int($options)) {
$error['status'] = $options;
}
}
$this->errors[$fieldKey][] = $error;
return $this;
}
/** * Validate a required field. * * @param mixed &$value The field value. * @param array $field The field definition. * @param Validation $validation A {@link Validation} object to collect errors. * @return bool|null Returns one of the following: * - null: The field is not required. * - true: The field is required and {@link $value} is not empty. * - false: The field is required and {@link $value} is empty. */ protected function validateRequired(&$value, array $field, Validation $validation) { $required = val('required', $field, false); $type = $field['type']; if ($value === '' || $value === null) { if (!$required) { $value = null; return true; } switch ($type) { case 'boolean': $value = false; return true; case 'string': if (val('minLength', $field, 1) == 0) { $value = ''; return true; } } $validation->addError('missing_field', $field); return false; } return null; }