I am having two models namely Patient Admission
having two columns such as admission_date
and discharge_date
and another model daily_ward_entry
having a date field say just date
both models are related by ipd_patient_id
Now What I want is to create one or two validators, so that I can restrict the date entry in daily_ward_entry
between admission_date
and discharge_date
I had a look at the compare validator
, but I can't make out, how to replace the value to be compared with attribute from another model with relation.
I have tried following variations, but it always throwing error:
Variation one
[$this->discharge_date, 'compare', 'compareValue' => $this->admission_date,
'operator' => '>='],
error - Unknown Property – yii\base\UnknownPropertyException
Variation two
['discharge_date', 'compare', 'compareValue' => 'admission_date', 'operator' => '>='],
error - Discharge Date must be greater than or equal to "admission_date".
This error is generated irrespective of date is lower or greater
variation three
[strtotime($this->discharge_date), 'compare', 'compareValue' =>
strtotime($this->admission_date), 'operator' => '>='],
error - Unknown Property – yii\base\UnknownPropertyException
I need some direction and help. Thanks.
You should be able to achieve your validation rule using a custom validator:
public function rules()
{
return [
['daily_ward_entry', 'validateDate'],
]
}
public function validateDate($attribute, $params) {
if(!($this->patientAdmission->admission_date <= $this->$attribute && $this->$attribute <= $this->patientAdmission->discharge_date)) {
$this->addError($attribute, 'The Daily Ward Entry must be between the admission date and the discharge date.');
}
}
Something like this should conceivably work, I am not entirely sure how your relations are set up so you'll likely have to modify that a little.
In this case you have to perform custom validation. in Custom function you will get all model data in POST, so you can get data and perform validation.