yii2 - How can I validate if the object belongs to the logged user, without manual validation? -
i'm using parent->child (master->detail) relation in yii2 active record
when user wants edit record, have validate if belongs user, in edit actions:
relation: client (1) ---> (n) comments
controller
class clientcontroller extends \yii\web\controller { public function actioneditcomment($id) { // validate if edited comment belongs user if (($comment = comment::findone($id)) == null || ($comment->client0->id != yii::$app->user->id) ) { throw new notfoundhttpexception('the requested page not exist.'); } if ($comment->load(yii::$app->request->post()) && $comment->save()) { return $this->redirect(['view-comment', 'id' => $comment->id]); } else { return $this->render('edit-comment', ['comment' => $comment]); } } } model
class comment extends activerecord { public function getclient0() { return $this->hasone(client::classname(), ['client' => 'id']); } } i have put code in edit , delete actions, prevent user changing comment id , edit or delete record not belong him
my final alternative validate belonging in model , call in edit , delete actions, wondering, if there other way go this?
you can kind of check accesscontroll filter in controller. , check in matchcallback parameter. example:
public function behaviors() { return [ 'access' => [ 'class' => accesscontrol::classname(), 'only' => ['edit-comment', 'delete-comment'], 'rules' => [ [ 'allow' => true, 'roles' => ['@'], 'matchcallback' => function($rule, $action){ $id = yii::$app->request->get('id'); if (($comment = comment::findone($id)) == null || ($comment->client->id != yii::$app->user->id) ) { return false; } else { return true; } } ], ], ], ]; } so yii2 call validation before run 'edit-comment' , 'delete-comment' actions.
Comments
Post a Comment