Hello and thanks in advance for reading this topic. I am an experienced PHP dev but pretty new to Yii and MVC frameworks in general. I have gone through several tutorials and made a few small apps using Yii but am still discovering the best ways to do certain things. I really like how simple it is to associate models using the relations() method and then access that data but my question is regarding when I am inserting or loading data and how I verify it belongs to a certain user. Associating a user id with a record seems pretty straightforward, I just add an extra line to the actionCreate method generated by gii after the $model->attributes statement:
$model->attributes=$_POST['Model'];
$model->user_id = Yii::app()->user->id;
Is this the correct way to do it or is there a more accepted/standard way to make sure the user_id field of my models is populated with the user who created a record?
Secondly, when I’m using the view/update/delete actions I want to make sure they are only accessible by the user who created them. Gii auto-generates the function loadModel in the controllers which has no validation so I ended up adding a new function to the Controller.php class in the Components directory called loadModelByUser:
public function loadModelByUser($modelname,$id)
{
$model = $modelname::model()->findByAttributes(array('id'=>$id,'user_id'=>Yii::app()->user->id));
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
Again, is there a better way to do this built into Yii which I missed in the tutorials?