How to restrict user by entering data for specific month where records greater than secific month exists in Yii2

I am using Yii2 basic. I have a table called groupsavingdetails which stores the monthly saving for each groups.

Suppose I have a group whose date of formation is 2017-08-08. Now while creating monthly saving records for this group I will select the group enter year as 2017 and month as August and enter all the values which will give me the closing balance for August and save in database.

Now when the user wants to make entry for October instead of september month he can do it as the system will show the August closing balance as opening balance and he will do the same for october month as done for august.

Now after making entry for october the user must not be able to enter record for september month.

I have records for this group for year 2017 and from months August, September, October, November and December.

What happens is that When I enter year as 2018 and month as January then alert message is displayed, which should not be displayed.

Here the condition is getting failed while saving the record

$group = Yii::$app->db->createCommand('SELECT *

    FROM groupsavingdetails

    where groupsavingdetails.GroupId=:id

    ORDER BY groupsavingdetails.GroupSavingDetailsId DESC LIMIT 1')


    ':id' => $model->GroupId,


 foreach($group as $groups)


  $identity = \Yii::$app->user->identity;
            $eid = $identity->id;
            $model->EmpId = $eid;






$previousMonth = $model->Month - 1;
if ($previousMonth == 0) {
    $previousMonth = 12;

if($model->Year>=$year2&&$model->Month>$previousMonth)   // Here the condition is getting failed.

echo "<script language='javascript'>";
                   echo "alert('Records greater than selected year and month exists.')";
                   echo "</script>";

                   return $this->render('create', [
                'model' => $model,

What should I change?