Data Validation
For value validation, you can use the Entity::getPreparedData
method
$fields = array(
'id_user' => array(
Entity::OPTION_KEY_TYPE => Entity::FIELD_TYPE_INT,
Entity::OPTION_KEY_REQUIRED => true,
),
);
$data = $this->getPreparedData($_POST, $fields);
if (!$data['id_user']) {
throw new SystemException(__('User ID is required'));
}
If you need to get the error text:
$fields = array(
'id_student' => array(
Entity::OPTION_KEY_TYPE => Entity::FIELD_TYPE_INT,
Entity::OPTION_KEY_REQUIRED => false,
),
'id_study_period' => array(
Entity::OPTION_KEY_TYPE => Entity::FIELD_TYPE_INT,
Entity::OPTION_KEY_REQUIRED => true,
),
);
$errors = array();
$data = $this->getPreparedData($_POST, $fields, $errors);
if (!empty($errors)) {
throw new SystemException(array_shift($errors));
}
protected function getFields(): array
{
return array(
'page' => array(
Entity::OPTION_KEY_TYPE => Entity::FIELD_TYPE_INT,
Entity::OPTION_KEY_DEFAULT => 1,
),
'order_by' => array(
Entity::OPTION_KEY_TYPE => Entity::FIELD_TYPE_STRING,
Entity::OPTION_KEY_DEFAULT => 'DESC'
),
);
}
Available Options
OPTION_KEY_DEFAULT
- sets the default value if the field is not presentOPTION_KEY_ERROR
- sets the error text if the field is not presentOPTION_KEY_FILTER
- sets the filter type for applying filter_varOPTION_KEY_OBJECT_TYPE
- specifies the class/interface to which the object contained in the value should belongOPTION_KEY_REGEXP
- sets a regular expression for validationOPTION_KEY_REQUIRED
- indicates whether the field is mandatoryOPTION_KEY_TYPE
- indicates what type the value should be converted to (Available value types)OPTION_KEY_RULE
- specifies a function for custom validation rules
Available Value Types
FIELD_TYPE_ARRAY
FIELD_TYPE_BOOL
FIELD_TYPE_FILE
FIELD_TYPE_FLOAT
FIELD_TYPE_INT
FIELD_TYPE_JSON
FIELD_TYPE_METHOD
FIELD_TYPE_OBJECT
FIELD_TYPE_SECURITY_STRING
FIELD_TYPE_STRING
FIELD_TYPE_STRING_NULL
Example of OPTION_KEY_RULE
public function testGetPreparedDataCustomRulePositive(): void
{
$fields = array(
'id' => array(
Entity::OPTION_KEY_TYPE => Entity::FIELD_TYPE_INT,
Entity::OPTION_KEY_RULE => static function ($value, ?string &$error) {
if ($value < 1) {
$error = 'Must be greater than 0!';
return false;
}
return $value;
},
),
);
$errors = array();
$data = $this->entity->getPreparedData($_REQUEST, $fields, $errors);
}