K
K
Kirill Tekord2017-10-11 02:48:50
Yii
Kirill Tekord, 2017-10-11 02:48:50

What is the best way to implement re-validation of a form whose fields are converted from string to \DateTime?

Let's say we have a model:

class ProductDatesCheckerForm extends Model {
       const INPUT_DATE_TIME_FORMAT = "d.m.Y H:i";

  /**
   * @var string
   */
  public $startDateTime;

  /**
   * @var string
   */
  public $endDateTime;

  /**
   * @var array
   */
  public $productReferences = [];

  /**
   * @inheritDoc
   */
  public function rules() {
    return [
      [['startDateTime', 'endDateTime', 'productReferences'], 'required'],
      [['startDateTime', 'endDateTime'], 'datetime', 'format' => self::INPUT_DATE_TIME_FORMAT],
      [['productReferences'], 'safe']
    ];
  }
}

As you can see from the validation rules, the format is specified for the time fields. After the model is validated, I want to convert all dates to a \DateTime object so that these values ​​can be used in calculations. In order not to produce additional objects, I convert the dates directly in this model, replacing the original text values ​​with an object of the \DateTime type. However, if I validate the model, there will be an error because the fields do not match the required format.
Question: how can I organize everything so that after converting dates to \DateTime there are no problems with validation? Of course, it makes sense to call validation only at the beginning, after loading the model, but still, purely academic interest.
The first idea was to add a when to the datetime validator, but this function only takes $model and there is no reference to the validator being validated to see which attributes are being validated. The named validation rule (`'myDates' => [['startDateTime', 'endDateTime'], 'datetime' ...'`) is also not suitable, because when the validation is first called, the validators from the rules() are instantiated, the Model::createValidators method does not take into account the keys in the rules() arrays. Accordingly, there is no way to get a specific validator at runtime.
The second idea is to add the $isConverted checkbox, and check the value in when . If true then ignore validation.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
mitaichik, 2017-10-11
@tekord

You can write a custom validator in which you will check the type and validate depending on it.
But storing data in different types in the same field is a very, very bad idea. Go around huge problems in the future. Better make a couple of methods that will convert to DateTime. Or keep only DateTime in the fields, and convert the strings as you fill in the data.

D
Dmitry, 2017-10-11
@slo_nik

Good morning.
Try like this:
yii\validators\DateValidator

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question