【问题标题】:Symfony2 : Form Validation with CollectionSymfony2:带有集合的表单验证
【发布时间】:2016-03-18 12:13:05
【问题描述】:

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

我尝试使用this link 解决我的问题,但没有成功。

这是我实体的一部分:

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';
    }
}

【问题讨论】:

    标签: php validation symfony


    【解决方案1】:

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

    解决方法如下:

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

    【讨论】:

      【解决方案2】:

      您需要自定义 http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多