Reputation: 53
How to be sure that min < max before validation
here my entity
/**
* @var int
*
* @ORM\Column(name="min", type="integer", nullable=true)
*/
private $min;
/**
* @var int
*
* @ORM\Column(name="max", type="integer", nullable=true)
*/
private $max;
in the form :
->add('min', NumberType::class,array('required' => false))
->add('max', NumberType::class,array('required' => false))
it's an option and min must be inferior to max before validating the form
How can i verify and send a message to the user to change his form if it's not correct.
Thanks
Upvotes: 3
Views: 8126
Reputation: 2014
Luckily, there is a better solution for Symfony >3.4.
GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual validation constraints come with propertyPath
option which allows to specify object property to compare with.
I am quite surprised that it was not implemented earlier.
/**
* @Assert\LessThanOrEqual(
* message="Too high",
* propertyPath="maxSubscribers")
* @Assert\LessThanOrEqual(
* message="Too high",
* value=100000000)
*/
private $min;
/**
* @Assert\GreaterThanOrEqual(
* message="Too low",
* value=1)
* @Assert\LessThanOrEqual(
* message="Too high",
* value=100000000)
*/
private $max;
Upvotes: 2
Reputation: 2654
You can write min
and max
validation in form
for .ex:
->add('ordering', NumberType::class, array(
'attr' => array('min' => 1, 'max' => 100)
))
Also in Entity
:
// src/Entity/YourFoo.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class YourFoo
{
/**
* @Assert\Range(
* min = 120,
* max = 180,
* minMessage = "You must be at least {{ limit }}cm tall to enter",
* maxMessage = "You cannot be taller than {{ limit }}cm to enter"
* )
*/
protected $fooNumber;
...............................
}
Upvotes: 0
Reputation: 17166
There are multiple ways to approach this that I can think of.
Probably the latter is the easiest one. Basically it looks something like this:
/**
* @Assert\Type("integer")
* @Assert\Expression("this.getMin() <= this.getMax()")
*/
private $min;
/**
* @Assert\Type("integer")
*/
private $max;
See: https://symfony.com/doc/current/reference/constraints/Expression.html
Creating a custom constraint is even more work than the Callback-constraint, so I won't go into details for that, but you can find a good article in the documentation.
Upvotes: 3