Syllz
Syllz

Reputation: 340

Symfony4: Validate DateIntervalType

I am currently stuck on a probably very simple question.

How do I validate my DateIntervalType to be != 0 - meaning atleast something has been selected. And how do I set a minimum/maximum: for example minimum interval of 1 day.

Background: I want to send an email every X years/months/days depending on the user select - an interval of 0 would mean permanent email sending, which I do not want.

Sadly I did not find anything helpful yet. Also tried integer assertations like @Assert\GratherThan etc. but that does not work.

Thanks in advance

Upvotes: 1

Views: 412

Answers (2)

Syllz
Syllz

Reputation: 340

Solution: Thanks to @Arleigh Hix for putting me on the right direction.

I solved my problem with following solution:

/**
 * @Assert\Expression("this.checkInterval()")
 */
private $interval;

public function checkInterval() {
    return $this->getTimestamp()->add($this->getInterval()) > $this->getTimestamp(); //getTimestamp() returns a DateTime
}

So basically just add the interval to any date and compare the new date to the initial date. With this way you can also get the difference in seconds and compare for min max values.

Better practise is probably to create a custom validator which will be my next step.

Upvotes: 2

Arleigh Hix
Arleigh Hix

Reputation: 10877

It looks you should be able to use an Expression constraint Maybe like this (I'm not sure about syntax for constructing the \DateInterval in the annotation)

/**
 * @Assert\Expression(
 *     "value >= minimum",
 *     values = { "minimum": new \DateInterval('P1D') }
 * )
 */
$dateIntervalField;

Alternatively, you should be able to set your minimum interval to an entity property and then compare value to that.

public function __construct()
{
  $this->minInterval = new \DateInterval('P1D');
}

/**
 * @Assert\GreaterThanOrEqual(
 *     value = this.minInterval
 * )
 */
$dateIntervalField;

Upvotes: 0

Related Questions