Validade A Related Attribute

Hello Guys,

I have a schema like this:




tbl_root:

 id

 user_id

 name


tbl_node:

 id

 user_id

 root_id

 name



In my NodeModel.php, I need a rule to check if attribute root_id belongs to the same user_id.

I’m trying the inLine validator, with this function:


public function attUserId($attribute) {

		if ($this->$attribute->user_id !== Yii::$app->user->id) {

			$this->addError($attribute, 'must be the same user_id');

		}

But of course it’s not working.

How can I change $this->$attribute->user_id and get this works?

Thanks!

There are some errors in the way you are calling user_id in your NodeModel. You also do not need parameters to your inline validator… you can do this:




public function attUserId() 

{

    if (!$this->hasErrors() && $this->user_id !== Yii::$app->user->id) {

        $this->addError('user_id', $this->user_id . ' must be the same user_id');

    }

}



Hello Kartik V, thanks again! But it’s not working this way.

Let’s see my data:




tbl_root:

 id   user_id   name

  1      1      root1

  2      2      root2


tbl_node:

 id   user_id   root_id  name

  1      1         1     node1  <-- this is ok

  2      2         2     node2  <-- this is ok

  3      1         2     node3  <-- this must be blocked by the rule



User_id->1 can not have a node with root_id->2, because this root doesn’t belong to him.

Any other sugestion?

Thanks very much!

You had not mentioned it clearly earlier… yes your query and validation needs to change (not sure why you have the user_id column again in Node table - since you could get it from the Root table)




public function attUserId() 

{

    if (!$this->hasErrors() && $this->root->user_id !== Yii::$app()->user_id) {

        $this->addError('user_id', $this->root->user_id . ' must be the same user_id');

    }

}


// your relation to RootModel

public function getRoot() 

{

   return $this->hasOne(RootModel::classname(), ['id'=>'root_id']);

}



You may add an additional condition to validate $this->user->id if needed. Do not know your complete scenario. Depends on when you populate the user_id in your NodeModel (at create and update).

Thanks again Kartik V, now it’s perfect!

Best Regards

just in case someone need this kind of validation, this is my generic function in BaseModel:




public function attUserId($attribute, $params)

{

   if (!$this->hasErrors() && $this->$params['relation']->user->id !== Yii::$app->user->id) {

	$this->addError('user_id', $this->$params['relation']->user_id . ' must be the same user_id');

   }

}



And in the model you want validade, this is the code for rules():




[['node'], 'attUserId', 'params' => ['relation' => 'root']]