繁体   English   中英

Symfony2:使用集合进行表单验证

[英]Symfony2 : Form Validation with Collection

我使用断言来检查表单的值。 我无法在集合上使用断言。 主要目标是检查每个值是否不为空并且是一个数字。

我尝试使用此链接来解决我的问题,但没有成功。

这是我的实体的一部分:

namespace MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

class Myclass
{

    private $id;    
    /**
     * @Assert\NotBlank()
     * @Assert\Regex(pattern="/^0[1-9]([-. ]?[0-9]{2}){4}$/",message="Invalid")
     */
    private $numbers;

    ...



    public function __construct()
    {
        $this->numbers= new ArrayCollection();
    }

    ...

    public function addNumber($number)
    {
        $this->numbers[] = $number;
        return $this;
    }

    public function removeNumber($number)
    {
        $this->numbers->removeElement($number);
    }

    public function getNumbers()
    {
        return $this->numbers;
    }
}

这是我表格的一部分:

namespace MyBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MyclassType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
        ->add('numbers',"Symfony\Component\Form\Extension\Core\Type\CollectionType",array(
            'required'=>true,
            'prototype' => true,
            'allow_add' => true,            
            'allow_delete' => true,
            'entry_type'=>"Symfony\Component\Form\Extension\Core\Type\TextType",
            'entry_options'   => array(
                'required'  => true,
                'attr'      => array('class' => 'form-control'),
                )
            )
        );
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
          'data_class' => 'MyBundle\Entity\Myclass'
        ));
    }

    public function getBlockPrefix()
    {
        return 'mybundle_myclass';
    }
}

“全部”断言似乎是 全部工作 (The Symfony Reference)

这是解决方案:

/**
 * @Assert\All({
 *     @Assert\NotBlank(),
 *     @Assert\Regex(pattern="/^0[1-9]([-. ]?[0-9]{2}){4}$/",message="Invalid")
 * })
 */
private $numbers;

你需要做一个自定义http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

这是我用来查找唯一实体的一个很好的例子: How to validate unique entity in an entity collection in symfony2您可以更改逻辑以检查值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM