I am right now getting myself more and more familiar with Zend Framework 2 and in the meantime I was getting myself updated with the validation part in Zend Framework 2. I have seen few examples how to validate the data from the database using Zend Db adapter, for example the code from the Zend Framework 2 official website:
//Check that the username is not present in the database
$validator = new Zend\Validator\Db\NoRecordExists(
array(
'table' => 'users',
'field' => 'username'
)
);
if ($validator->isValid($username)) {
// username appears to be valid
} else {
// username is invalid; print the reason
$messages = $validator->getMessages();
foreach ($messages as $message) {
echo "$message\n";
}
}
Now my question is how can do the validation part?
For example, I need to validate a name before inserting into database to check that the same name does not exist in the database, I have updated Zend Framework 2 example Album module to use Doctrine 2 to communicate with the database and right now I want to add the validation part to my code.
Let us say that before adding the album name to the database I want to validate that the same album name does not exist in the database.
Any information regarding this would be really helpful!
I had the same problem and solved it this way:
NoEntityExists
(or whatever you want).Zend\Validator\AbstractValidator
Doctrine\ORM\EntityManager
isValid($value)
method that checks if a record exists and returns a booleanEntityManager
and use it just like any other validator.To get an idea of how to implement the validator class, check the validators that already exist (preferably a simple one like
Callback
orGreaterThan
).Hope I could help you.
// Edit: Sorry, I'm late ;-)
So here is a quite advanced example of how you can implement such a validator.
Note that I added a
translate()
method in order to catch language strings with PoEdit (a translation helper tool that fetches such strings from the source codes and puts them into a list for you). If you're not usinggettext()
, you can problably skip that.Also, this was one of my first classes with ZF2, I wouldn't put this into the
Application
module again. Maybe, create a new module that fits better, for instanceMyDoctrineValidator
or so.This validator gives you a lot of flexibility as you have to set the query before using it. Of course, you can pre-define a query and set the entity, search column etc. in the options. Have fun!
if you use the DoctrineModule, there is already a validator for your case.