3

I use assert to check values of my form. I am not able to work with assert on a collection. The main goal it to check if each values are not empty and is a number.

I tried to use this link to solve my issue without success.

Here is part of my entity :

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

And here is a part of my form :

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';
    }
}
Inglebard
  • 427
  • 5
  • 14

2 Answers2

2

"All" assert seems to be the job All (The Symfony Reference)

Here is the solution :

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

You'll need to make a Custom http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

This has a good example that I use to find a unique entities: How to validate unique entities in an entity collection in symfony2 You can change the logic to check values.

Community
  • 1
  • 1
Cathmor
  • 59
  • 1
  • 7