【问题标题】:Symfony2 callback validation set error on property of fieldSymfony2回调验证设置字段属性错误
【发布时间】:2012-11-08 10:28:10
【问题描述】:

我在 Symfony 2.0.4 中使用回调验证器来验证嵌入表单的集合。我正在尝试查看其中一个表单的字段是否在任何表单中重复,如果是,则在该字段上添加错误。
代码如下:

/**  
 * @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;
                }
            }
        }
    }
}  

$prices 字段是一个 Price 实体数组,每个实体都有 country 属性。国家也被添加到表单类型中。
我只想在 country 属性上添加错误,但似乎 Symfony 不允许我指定比 $propertyPath.'.field' 更复杂的任何内容。
谁能告诉我 $propertyPath 的语法是什么,它允许我在层次结构中指定一个较低级别的字段集?

更新:

似乎验证已正确完成,在研究了 PropertyPath 类构造函数后,我确定我使用的路径是正确的。问题是指定的消息未按预期显示在国家/地区字段上。

【问题讨论】:

标签: forms symfony collections validation


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多