Form Validation with data from DB

Hi! I just want to know how to do field validation with data from DB. It’s like this. I’m actually making a leave management system. So I have a “from” and “to” fields as dates. I want to compute the total days using those two fields and compare it to the leave quota stored in the DB. If the total days are greater than the quota in the DB it will return an error in the form. So how do I do that?

Thank you in advance!

Guys, any suggestions???..

Write a validator method in your model and assign it to "to" attribute in rules(). In method, use DateTime::diff() to calculate the difference, compare it with the stored quota, and use CModel::addError() when needed.

This is my validator function.




	public function leaveQuota(){

		if ($this->type == 'Vacation')

			$quotaType = 'vlQuota';

		else if ($this->type == 'Sick')

			$quotaType = 'slQuota';

		else if ($this->type == 'Maternity')

			$quotaType = 'mlQuota';

		

		$difference = date_diff(date_create($this->from), date_create($this->to));

		

		$leaveQuota = LeaveQuota::model()->findByAttributes(array('staff_id'=>Yii::app()->user->id));

		if($difference > $leaveQuota->$quotaType)

			CModel::addError('to', 'You have not enough leave quota for that type.');

	}



The problem is it keeps on returning the error even if the difference is within the quota. I think the problem is the data that I’m getting from the ‘type’ attribute. The ‘type’ attribute is a drop-down. Maybe because I’m not getting data from the ‘type’ attribute.

I just solved it! I just forgot to define the format of the datetimeInterval and it should be :


$difference->format('%a')

Thanks phtamas!