【问题标题】:Symfony2 form builder without class check if multiple fields are emptySymfony2表单构建器没有类检查多个字段是否为空
【发布时间】:2015-06-19 17:30:46
【问题描述】:

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

$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);

这很好用,但我想检查两个字段是否都是空的,并显示错误。只是似乎无法处理这个问题。有人可以提供帮助吗???

【问题讨论】:

  • 在两个表单字段中都执行 'required'=>true。

标签: validation symfony constraints formbuilder


【解决方案1】:

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

但是..在帖子中您可以像这样简单地检查

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,尤其是这个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);
            }
    }
}

【讨论】:

  • 其实 'required' => false 是我想要的。如果两个字段都为空,只需要捕获。谢谢你。有用。不过,我想知道是否可以使用验证组或回调来处理这个问题?只是想了解更多...
【解决方案2】:

在您的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 ...;

        }

【讨论】:

  • 谢谢。我没有在这方面使用实体。而且我确实想在一个字段上允许空白,但在两个字段上都不允许空白。我想知道是否可以添加到 createFromBuilder 结构中,以检查两者是否为空白。
猜你喜欢
  • 2012-06-21
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
  • 2012-03-01
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多