I have a form where the required validation rules for the fields can be configures and stored in the model.
When rendering the form, I create the validation rules as follows (simplified) which works fine.
$view_parameters = $competition_article->view_parameters;
if (!empty($view_parameters) && is_array($view_parameters)) {
foreach ($view_parameters as $parameter_key => $parameter_value) {
$field_name = $parameter_value['name'];
$field_required = $parameter_value['required'];
if ($field_required) {
Validator::createValidator('required', $model, [$field_name]);
}
}
}
For the form submission, I use a custom validation rule. This works for all but the file attachment.
public function rules()
{
$rules = [
[['firstname', 'surname', 'closeststore', 'email', 'phone', 'response', 'attachment'],
'dynamicValidator',
'skipOnEmpty' => false
],
[['attachment'], 'file',
'extensions' => 'pdf, jpeg, jpg, doc, docx',
'checkExtensionByMimeType'=>false
],
];
return $rules;
}
On the custom validation method, I handle the file separately. I tried a) addError() and return false b) createValidator() and validateAttribute() pair , which works for the text fields.
public function dynamicValidator($attribute, $params, $validator )
{
$view_parameters = $this->view_parameters;
if ($view_parameters[$attribute]['required'])
$validator = new Validator();
if ($attribute == 'attachment') {
if (empty($_FILES['CompetitionForm']['name']['attachment']))
[$attribute]);
$this->addError( $attribute, 'Please include your attachment to enter.');
// NOTE : Adding the validator has no effect
// $validator = $validator->createValidator('required', $this,
// $validator->validateAttribute($this, $attribute);
return false;
}
$validator = $validator->createValidator('required', $this, [$attribute]);
$validator->validateAttribute($this, $attribute);
}
}
Despite the code being reached, an error is not raised when the attachment is require and the either the addError() or createValidator() is called.
How can I fail the validation when no file is attached and the attachment is required?