Autor wpisu: Kamil Adryjanek, dodany: 06.03.2013 02:23, tagi: symfony2, php, symfony
Symfony2 comes with a very nice validation system and allows us for example to add a constraint to any public method whose cheap viagra name starts with „get” or „is” („Getters”) and not only. In combination with the Validation Groups it is a really powerfull tool. This time i want to show you how to map those errors.
Adding custom method to entity we can add some extra validations for example to address field:
<?php // some entity class /** * Checks if user provides a valid address * * @Assert\True(message = "user.address.invalid") */ public function isAddressValid() { // some logic }
Now this entity will be also checked against extra rules form isAddressValid method. That’s really cool and easy but there was one thing that forced me to choose Callback Validation and its:
$context->addViolationAt('address', 'user.address.invalid', array(), null);
instead of Getters in many cases: i was not allowed to assign errors to specific fields on my object. It means that i couldn’t make these errors display next to a specific field and they were displayed at the top of my form – since Symfony2.1 it’s not a problem any more.
Thank to new error mapping funcionality: „error_mapping” we can now set which method should be mapped to a given field”:
<?php class UserType extends AbstractType { public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'error_mapping' => array( // this line tells Symfony to assign Getter Constraint to address property 'addressValid' => 'address' ), )); } }
Since error_mapping is set, errors will be displayed next to address filed.
We can also use dot for building nested property paths and assign errors to embedded forms: ‚cityValid’ => ‚address.city’ or ‚address.cityValid’ => ‚city’ – depending on our needs.
Ecard Wizard Greeting Card Software zp8497586rq