Hi! Another way is to define your own validator for this and add it to the form. Example of a validator which communicates with other fields and generate error messages based on values of other field is this one:
Phalcon\Validation\Validator\Confirmation
. Look at https://docs.phalcon.io/en/latest/api/Phalcon_Validation_Validator_Confirmation.html.
So what I suggest you is to create your own validator, e.g. RefValidator
. You will simply add it to each Ref
field in all your forms. The validator will do all the work, it will check values of the targeted field and generate messages if needed.
So the usage of your new validator will look like this:
public function initialize{
$ref = new Text('ref', array(
'placeholder' => 'Ref',
'class'=>"form-control"
));
$ref->addValidator(new RefValidator(array(
'message' => 'Ref must be present',
`with` => 'method',
)));
$this->ref = $ref;
///other fileds here
}
And that's all, you will do NOTHING else. I think it is very simple to read such code, and to maintain it later.
So the last issue is how to create your own validator. Below is example of my StrictValidator
. It is extension of Phalcon's Phalcon\Validation\Validator\Confirmation
.
<?php
namespace Omcs\Common\Library\Validation\Validator;
use Phalcon\Validation\Validator,
Phalcon\Validation\ValidatorInterface,
Phalcon\Validation\Validator\Confirmation as ConfirmationValidator,
Phalcon\Validation\Message;
class StrictConfirmation extends ConfirmationValidator implements ValidatorInterface {
public function validate($validator,$attribute) {
//obtain the name of the field
$with = $this->getOption("with");
//obtain field value
$with_value = $validator->getValue($with);
$value = $validator->getValue($attribute);
//check if the value is valid
if($with_value === $value){
//value is valid
return true;//end of validation
}
//try to obtain message defined in a validator
$message = $this->getOption('message');
//if the message is not defined takes a standard one
if (!isset($message) OR !$message) {
$message = "The values are not the same.";
}
$validator->appendMessage(new Message($message, $attribute, 'StrictConfirmation'));
return false;
}
}
Suggest to read:
Phalcon rocks! ;)