没有 class 检查多个字段是否为空的 Symfony2 表单生成器

Symfony2 form builder without class check if multiple fields are empty

我正在使用不带 class 的表单生成器,并且有两个字段,每个字段都有约束:

$form = $this->createFormBuilder()
        ->add('name', 'text', array(
            'required'=>false,
            'constraints'=> new Length(array('min'=>3)
        ))
        ->add('dob', 'date', array(
            'required'=>false,
            'constraints'=> new Date()
        ))
        ->getForm()
        ->handleRequest($request);

效果很好,但我想检查两个字段是否为空,并显示错误。似乎无法解决这个问题。有人可以提供帮助吗???

最简单的解决方案是根据需要设置两者...

但是..在post你可以像

一样简单地检查
if( empty($form->get('name')->getData()) && empty($form->get('dob')->getData())){
   $form->addError(new FormError("fill out both yo"));
   // ... return your view
}else {

  // ... do your persisting stuff
}
... 

symfony 的方式可能是添加自定义验证器 我建议你看看 custom validator especially this part

伪:

namespace My\Bundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class CheckBothValidator extends ConstraintValidator
{
    public function validate($foo, Constraint $constraint)
    {
            if (!($foo->getName() && $foo->getDob()) {
                $this->context->addViolationAt('both', $constraint->message, array(), null);
            }
    }
}

在您的 Bundle->Resources->Config 文件夹中创建一个文件名 validation.yml 然后

namespace\YourBundle\Entity\EntityName:
    properties:
        dob://field that you want to put validation on 
            - NotBlank: { message: "Message that you want to display"}
        gender:
            - NotBlank: { message: "Message that you want to display" }

一旦您检查表单数据是否已提交,验证就会立即生效 isValid()

$entity = new Programs();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $this->get('session')->getFlashBag()->add(
                'notice',
                'Success'
            );
            //  your return here
            return ...;

        }