约束\回调注释验证先前(未提交)实体

时间:2016-03-08 21:12:11

标签: forms validation symfony

我使用Callback来验证实体

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\Foo")
 * @ORM\Table(name="foo")
 * @Constraints\Callback(methods={"validate"})
 */
class Foo
{
    ...

    function validate(ExecutionContextInterface $context)
    {
        if ($this->foos) {
            $context->buildViolation('Foos cannot be emty')
                ->atPath('foos')
                ->addViolation();
    }
}

表单正在使用此实体:

class FooFormType extends AbstractType
{
    private $foosService;

    function __construct(FoosService $foosService) {
        $this->foosService = $foosService;
    }
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('foos', EntityType::class, array(
                'label' => false,
                'class' => 'AppBundle:Entity\Foo',
                'choices' => $this->foosService->getSomeFoos($builder->getData()),
                'expanded' => true,
                'multiple' => true,
                'required' => true,
            ))
            ->getForm();
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Foo',
        ));
    }
}

此表单在工厂内调用:

public function getFooForm(Foo $foo)
{
    return $this->formFactory->create(new FooFormType($this->foosService), $foo);
}

最后,在控制器中:

...

$form = $this->get('my_factory')->getFooForm($foo);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
    $this->getDoctrine()->getManager()->flush();
    ...
}

...

这似乎工作正常,但正在对前一个实体进行验证。我的意思是,如果我提交空foos,我可以看到验证错误,但如果我汇总一些foos,然后我删除那些foos并再次提交,则验证不会抛出任何异常,因为它是在最后一个实体上完成的,它有一些foos。我已检查过提交的数据是否正确,实际上,Foo实体已保留为空foos(仅当前一个实体有foos时)。

可能导致这种奇怪行为的原因是什么?

0 个答案:

没有答案