Dawid Ohia
Dawid Ohia

Reputation: 16445

Entity form field and validation in Symfony2?

In my form I have field of type entity. How to disable validation of that entity when the form is submitted? This entity is already persisted in database, so there is no point for validator to validate this entity from my point of view.

EDIT:

Code looks like this:

class SearchRequest
{
    /**
     * @ORM\ManyToOne(targetEntity="ArticlePattern")
     * @ORM\JoinColumn(name="article_pattern_id", onDelete="CASCADE")
     * @Assert\NotBlank
     */
    private $articlePattern;
}

form field:

$builder
    ->add('articlePattern', 'entity', array('class' => 'LonbitItssBundle:ArticlePattern')

Validation groups won't work because what I want to accomplish is for validator to check the constraint @Assert\NotBlank on $articlePattern field, but I don't want him to check the constraints defined in class ArticlePattern. So in other words, I want prevent validator from descending inside the $articlePattern object, but I want the constraint placed on $articlePattern field itself to be validated.

Any idea how to do that?

EDIT2:

Validation groups will work. So the final solution is to add groups={"search_request"} constraint option (name of the group is arbitrary) to every field assertion in SearchRequest class, like this:

/**
 * @Assert\NotBlank(groups={"search_request"})
 */
private $articlePattern;

That way, validation won't descend to associated objects (assuming they don't belong to - in this case - "search_request" group).

Upvotes: 2

Views: 7045

Answers (1)

Sybio
Sybio

Reputation: 8645

1) If you want to disable this field, just don't use it in your class form ! (and remove it from the template)

public function buildForm(FormBuilder $builder, array $options)
{
        $builder
            ->add('content')
            ->add('username')
            //->add('yourEntity')
        ; 
}

2) Or better, use validation groups. You create a validation_group which don't call your validator entity and then you use this group in your class form:

public function getDefaultOptions(array $options)
{
        return array(
            'data_class' => 'Sybio\BuzzBundle\Entity\SearchRequest',
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            'intention'       => '865c0c0b4ab0e063e5caa3387c1a8741',
            'validation_groups' => array('without_article_pattern_ckecking'),
        );
}

In your Entity class:

/**
 * @ORM\ManyToOne(targetEntity="ArticlePattern")
 * @ORM\JoinColumn(name="article_pattern_id", onDelete="CASCADE")
 * @Assert\NotBlank(
 *  groups={"without_article_pattern_ckecking"}
 * )
 */
 private $articlePattern;

Your form will only validate validators that refer to without_article_pattern_ckecking group, so it should not test validators inside your ArticlePattern entity if they don't have this validation group.

I hope this helps you !

Upvotes: 4

Related Questions