DJ Far
DJ Far

Reputation: 506

Access Auth component in Model

I want to create a Behavior to automagically populate a 'created_by' field when a record gets saved with the id of the logged in user, much like timestamp does with 'created'. However, apparently you can get $this->Auth->user('id') everywhere except in the Model.

I am having to resort to updating the request data in the controller's add() method before the save() call, which works but it's not DRY. I'd like to have bake add the behavior in a model's table class for any entity that has a 'created_by' field.

Any ideas how I could do this in a Behavior, the way Cake intended?

Upvotes: 0

Views: 894

Answers (2)

ADmad
ADmad

Reputation: 8100

The Blame behavior does what you need. You can either use it or study it's code to implement your own.

Upvotes: 0

nIcO
nIcO

Reputation: 5001

A possibility is to use the Events System. I personaly did this by using a Component and a Behavior that communicate through the Model.beforeSave event. Basically the component is responsible to add a new listener that passes a function to the behavior allowing to retrieve the authenticated user id.

You can have a look at the code of both classes here: UserLinkComponent, UserLinkBehavior

and to use them:

Controller:

$this->loadComponent('Alaxos.UserLink');

Model\Table:

$this->addBehavior('Alaxos.UserLink');

Upvotes: 2

Related Questions