symfonyvalidationsymfony4symfony-validator

How to Validate an EntityType field?


I want to make sure that the user chooses an element from the dropdown list.

So I used * @Assert\NotBlank() in the entity file.

/**
 * @ORM\ManyToOne(targetEntity=Bord::class, inversedBy="cartes")
 * @ORM\JoinColumn(nullable=false)
 * @Assert\NotBlank()
 */
private $bord;

The problem is it always returns This value should not be blank. error on the form! Even when the user selects a value from the list.

I also used * @Assert\NotNull() too and I still get the same problem.

I can remove the Assert validation and hard code it by testing on the controller and using flash messages! But I want to use Assert Validation.

So How can I validate an EntityType Field?

In the formType:

->add('bord',EntityType::class,[
            'class'=>Bord::class,
            'choice_label'=>'ref_bord',
            'label'=>'Bord',
            'placeholder'   =>'Choose a Bord',
            'mapped' => false])

On the view:

{{ form_widget(form.bord, {'attr': {'class': 'form-control'} }) }}  
{{ form_errors(form.bord) }}

Solution

  • This is because your entity field not mapped. With 'mapped' => false the form doesn't put data into the entity, so it is always null.