Validation not working correctly in yii2

Hi,
I am using yii2 basic. I have a groupdetails table and CRUD.
I have groupsavingdetails table. One group has many group saving details.
Groupdetails - Table

  1. GroupId
  2. GroupName

Groupsavingdetails - Table

  1. GroupsavingdetailsId
  2. GrroupId
  3. Year

In the model of Groupsavingdetails, for Year field I have a rule which validates the year. The entered year must be greater than or = to the year in Date of Formation of the group selected. I have a method as below.

public function validateyear($attribute,$params,$validator)
	{
	    
	$group = Groupdetails::find()->where(['GroupId' => $this->GroupId])->all();
	  $year;
	  if ($group !=null) {
								
			foreach($group as $groups)
			{
			  $year= $groups['FormationDate'];
			}
			  $year1= explode('-', $year);
			  if($this->attribute<$year1[0])
				  $this->addError($attribute,'Year should be greater than or = to '.$year1[0]);		
	  }

    else
		   {
			  $this->addError($attribute,'Such group not there');
			}
			
			              
    }
		

Here if the Date of Formation is 2017-08-08, and the year entered by user is 2016, still the error message is not shown.

How to resolve error?

Hi James,

//Don't forget to set up your timezone to initial config
date_default_timezone_set("Asia/Bangkok"); //Important to use date() functions
function validateyear($attribute, $params, $validator) {
    //First don't retrieve all the records as in reverse relation Groupsavingdetails pk will have one fk in Groupdetails
    $group = Groupdetails::find()->where(['GroupId' => $this->GroupId])->one(); //Just get only that group
    if ($group != null) {
        $formationYear = date('Y', strtotime($group->FormationDate)); //Convert to proper date from db
        if ((int) $this->attribute < (int) $formationYear) //Strictly do the mathematical calculations over here
            $this->addError($attribute, 'Year should be greater than or = to ' . $year1[0]);
    } else {
        $this->addError($attribute, 'Such group not there');
    }
}
1 Like