Reputation: 159
I have user.yml file in my validation folder in symfony and I am using it to validate the data. eg:
\APIBundle\Entity\User:
properties:
startDate:
- NotBlank: { message: 'Start date cannot be blank.' }
- Date: { message: 'Enter the valid start date.' }
I wanted to validate "startDate" field if user have passed it which is working now. But if user is not passed the "startDate" then I wanted to skip this validation. i.e Wanted the this validation as optional .
How to achieve this ?
I tried to set required false as following:
\APIBundle\Entity\User:
properties:
startDate:
- Required: false
- NotBlank: { message: 'Start date cannot be blank.' }
- Date: { message: 'Enter the valid start date.' }
Which is not working symfony return the error
Upvotes: 1
Views: 1266
Reputation: 722
required just affects rendering see :
If true, an HTML5 required attribute will be rendered. The corresponding label will also render with a required class.
This is superficial and independent from validation. At best, if you let Symfony guess your field type, then the value of this option will be guessed from your validation information.
you should use empty_data
in your form like so :
$builder->add('gender', ChoiceType::class, array(
'choices' => array(
'm' => 'Male',
'f' => 'Female'
),
'required' => false,
'placeholder' => 'Choose your gender',
'empty_data' => null
));
Your entity in this case should have the property nullable=true
and of course like mentionned NotBlank
shouldn't be used
Upvotes: 1
Reputation: 2379
Just remove NotBlank
\APIBundle\Entity\User:
properties:
startDate:
- Date: { message: 'Enter the valid start date.' }
NotBlank
is equivalent of reqired
.
Upvotes: 0
Reputation: 1186
Since you're using NotBlank
, that field is always required. However, you only want to validate the field if it is actually set.
I think that you won't accomplish that with Symfony's built-in validation, but you could write your custom Validation Constraint that handles this case: http://symfony.com/doc/current/cookbook/validation/custom_constraint.html
Upvotes: 0