使用表单更新对象后,对于其中一个字段(foo
)中的某个值,我想检查是否存在具有特定属性值的持久子对象。
所以我创建了一个自定义验证器,将doctrine作为参数传递,但是..如何传递对象(或对象的id)和foo
的特定值来创建查询?
这是我的代码:
class ChildCategoryHasItsOwnPageValidator extends ConstraintValidator
{
protected $doctrine;
public function __construct(RegistryInterface $doctrine)
{
$this->doctrine = $doctrine;
}
public function validate($value, Constraint $constraint)
{
//...
}
}
Placas\FrontendBundle\Entity\Category:
properties:
ownPage:
- Placas\FrontendBundle\Validator\Constraints\ChildCategoryHasItsOwnPage: ~
/**
* @Annotation
*/
class ChildCategoryHasItsOwnPage extends Constraint
{
public $message = 'This category has a child category with an own page. You can not define an own page for this category.';
public function validatedBy()
{
return "child_category_has_its_own_page";
}
}
Placas\FrontendBundle\Entity\Category:
properties:
ownPage:
- Placas\FrontendBundle\Validator\Constraints\ChildCategoryHasItsOwnPage: ~
答案 0 :(得分:0)
我想这会对你有所帮助:http://symfony.com/doc/current/reference/constraints/Callback.html
它应该像你这样工作: (Symfony 2.4版)
您的配置:
Placas\FrontendBundle\Entity\Category:
constraints:
- Callback: [validate]
在你的实体中:
use Symfony\Component\Validator\ExecutionContextInterface;
class Category
{
public function validate(ExecutionContextInterface $context)
{
$children = $this->getChildren(); // assuming you have this relationship and its getter
foreach ($children as $child)
{
if ($child->foo != '') // or whatever test you want to make
{
$context->addViolationAt(
'foo',
'This category has a child category with an own page. You can not define an own page for this category.',
array(),
null
);
}
}
}
}