Bogdan
Bogdan

Reputation: 913

Symfony2 callback validation set error on property of field

I'm using the callback validator in Symfony 2.0.4 to validate a collection of embedded forms. I'm trying to see whether one of the forms' fields is duplicated in any of the forms and if so to add an error on that field.
Here is the code:

/**  
 * @Assert\Callback(methods={"isPriceUnique"})  
 */  
class Pricing {  
    protected $defaultPrice;  
    protected $prices;  

    public function isPriceUnique(ExecutionContext $context){
    //Get the path to the field that represents the price collection
    $propertyPath = $context->getPropertyPath().'.defaultPrice';
    
    $addedPrices = $this->getPrices();
    \array_unshift($addedPrices, $this->getDefaultPrice());
    
    for($i=0; $i<\count($addedPrices); $i++){
        $price=$addedPrices[$i];
        $country=$price->getCountry();
        
        //Check for duplicate pricing options(whose country has been selected already)
        if($i<\count($addedPrices)-1){
            for($j=$i+1; $j<\count($addedPrices); $j++){
                if(\strcmp($country, $addedPrices[$j]->getCountry())==0){
                    $context->setPropertyPath($propertyPath.'.'.$j.'.country');
                    $context->addViolation('product.prices.unique', array(), null);
                    break;
                }
            }
        }
    }
}  

The $prices field is an array of Price entities, each having the country property. The country is added to the form type as well.
I would like to add the error on the country property only, but it seems that Symfony does not allow me to specify anything more complex than $propertyPath.'.field'.
Could anyone tell me which is the syntax for $propertyPath which would allow me to specify a field set on a lower level in the hierarchy?

Update:

It seems that the validation is done properly and after studying the PropertyPath class constructor I am certain that the path that I've used is correct. The issue is that the specified message is not displayed on the country field, as expected.

Upvotes: 0

Views: 1755

Answers (1)

Asmir Mustafic
Asmir Mustafic

Reputation: 543

You can use $context->addViolationAt()

http://symfony.com/doc/2.2/reference/constraints/Callback.html#the-callback-method

Upvotes: 0

Related Questions