Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 using validation groups in form

I have a Entity with a property:

/**
 * @var string $name
 *
 * @Assert\NotBlank(groups={"foobar"})
 * @ORM\Column(name="name", type="string", length=225, nullable=false)
 */
private $name;

The Form:

class MyType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('name');
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => '...',
            'validation_group' => array('foobar'),
        );
    }

    public function getName()
    {
        ...
    }
}

In the Controller I bind the Request and call $form->isValid()

But how to define the validation_group?

like image 570
Uwe Avatar asked Sep 06 '11 15:09

Uwe


4 Answers

From inside your FormType class you can define the validation groups associated to that type by setting your default options:

public function getDefaultOptions(array $options)
{
    return array(
        'data_class' => 'Acme\MyBundle\Entity\MyEntity',
        'validation_groups' => array('group1', 'group2'),
    );
}
like image 102
Jeremy Avatar answered Oct 19 '22 03:10

Jeremy


I had exactly the same problem. I solved it that way ...

// Entity
$employee = new Employee();

// Form creation
$form = $this->createForm(new EmployeeForm(), $employee, array('validation_groups'=>'registration'));

I hope that helps!

like image 38
Jernej Gololicic Avatar answered Oct 19 '22 03:10

Jernej Gololicic


When building the form in the controller, add a 'validation_groups' item to the options array:

$form = $this->createFormBuilder($users, array(
    'validation_groups' => array('foobar'),
))->add(...)
;

It is described in the forms page of the symfony2 book: http://symfony.com/doc/current/book/forms.html#validation-groups

like image 37
Neil Katin Avatar answered Oct 19 '22 01:10

Neil Katin


For me, on symfony 2.1, i solved it by adding 'Default' in validation_groups like:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Acme\MyBundle\Entity\MyEntity',
        'validation_groups' => array('Default', 'registration')
    ));
}
like image 30
Harold Avatar answered Oct 19 '22 01:10

Harold