I am using CakePHP and want to pass the author's name (stored in a session) to an article that is being saved to the database. Is a hidden field the only way to do this or is there a better way?
A:
There are other ways, but a hidden field is as convenient as any other and probably the most transparent (i.e. most detectable by other developers who may pick up the code later). You could also insert the value into the $this->data
structure before save and be sure that your model knows what to do with it.
Rob Wilkerson
2010-08-19 16:16:30
A:
If you already have it in the session, I would not spend the extra code/time to add it to a hidden field. I would update the method to add the session variable to the $this->data so it will add it when you save the record. So the method in the controller would look something like:
function add() {
if($this->data) {
$this->data['Article']['author'] = $this->Session->read('User.name');
$this->Article->create();
if ($this->Article->save($this->data)) {
...
}
This way you are not dealing with all the extra work and you can still achieve the results you are looking for.
cdburgess
2010-08-19 16:43:18
Brilliant! One note for anyone else reading this thread that is using CakePHP's Auth component, like me: It needs to be $this->Session->read('Auth.User.name');. Thanks for the help- truly appreciated!
Justin
2010-08-19 19:31:55
Glad to help! Happy coding!
cdburgess
2010-08-19 20:41:05