开发者

Proper way to inject Session data before model save/validate in CakePHP 1.3?

Using CakePHP 1.3.6

I'm using a login-less authentication via a unique value as an URL param, so that when an "invited" user accesses a supplied link, I know who they are, and set some user information in the Session.

On t开发者_StackOverflow中文版his page is a form, with a parent and related child models (hasMany, belongsTo, all that).

Each child model has an 'agent_id' field (FK to Agent model, which is loaded upon accessing the page) that needs to be populated with an ID previously loaded in the Session.

Do I have to create a hidden input field for "agent_id" next to every child model form element group, or is there an easier way?

Perhaps I can grab from the Session or something from within the Model/Behavior beforeValidate() or some such? That would be ideal, but I'm not sure how.

Thanks!


It's not a good practice (in MVC pattern) to call session values from Model. This value should be supplied by the action.

Creating hidden input is not great idea, because user can modify it.

So your code should be something like.

if (!empty($this->data)) {
    $this->Model->create();
    $this->data['Model']['agent_id'] = $this->Auth->user('id');
    if ($this->Model->save($this->data)) { 
         // success
    }
}

EDIT

Yes, you can read sessions from Model, but its not recommended. Because it actually breaks the MVC architecture. If you wont care much you can use

// in your Model.php
App::import('Model', 'CakeSession');
$session = new CakeSession();

References

  1. Using Session Vars in a MVC Domain Model library
  2. http://groups.google.com/group/cake-php/browse_thread/thread/163bd9b60aa8757b/80163f0de8c54ad1?lnk=raot&pli=1
  3. http://cakephp.1045679.n5.nabble.com/Checking-user-session-in-model-td1294422.html
  4. read more
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜