Yii Framework Automate setting the "owned by user" attribute to the currently logged in user

alfa6661
- February 09, 2013
0 (0 votes)
Rate :
Automate setting the "owned by user" attribute to the currently logged in user

This is just a very simple snippets to automate set "owned by user" attribute to the currently logged in user id upon creation of a record.

Assuming a dataset is "owned" by a user, we need to set the id of the current logged in user when saving the dataset automatically. We will use beforeSave() to set this attribute. This method is invoked before saving a record (after validation, if any).

public function beforeSave()
{
    $this->user_id = Yii::app()->user->id;
    return parent::beforeSave();
}

Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter

– Eric S. Raymond

Have a better explanation?

If you have comments about this post. Please write your comments below

No comments associated with this article