tags:

views:

36

answers:

1

I recently started using CakePHP and am trying to define User-specific "field" preferences. Basically, I want each user to be able to specify which fields he/she wants to see in a table.

To do this, I have a users table, a fields table, and a fields_users table. The last table is just a field_id and user_id, so the code knows to link that field with that user.

So far, I have created a controller/model for 'User' and a controller/model for 'Fields', and am linking them with the hasAndBelongsToMany property. For instance, in the 'Field' model, I have the following property defined:

` var $hasAndBelongsToMany = array (

  'User' => array (
   'className' => 'User',
   'foreign_key' => 'field_id',
   'join_table' => 'fields_users',
   'fields' => array( 'User.id' ),
   'conditions' => array( 'User.id' => 2 ),
   'unique' => false,

) );`

As you can see above, the 'User.id' in the 'conditions' part of the array is hard-coded.

My question is this: How can I make it so that the 'conditions' part of this property is set to be the current user's id?

Obviously, I only care about the current user's field preferences, but at the moment I'm getting everyone's user info.

Setting it to be a variable in the initial property definition doesn't work, and I'm not sure at what point I should be doing this (or if there's a better way entirely). (doing it in beforeFilter didn't work, and I can't seem to access $_SESSION from the model's __construct function)

A: 

Do it from the controller. You can get the current user id by $this->Auth->user('id').

bancer
Let me be more clear--I know how to get the user id, etc., and I know how to set the 'hasAndBelongsToMany' property from both the controller and the model. The problem is that even if I modify the 'hasAndBelongsToMany' property in the 'beforeFilter' function in the controller, it appears that critical code using that property has already been executed, and the conditions are not taken into accountAll I want is to be able to get some sort of data structure that includes the information about the field as specified for the current user. Right now, I can get this, but I get it for every user.
GTT
What is your code in `beforeFilter()`?
bancer
I just changed it to the following, and it seems to be working now.`function beforeFilter() { parent::beforeFilter(); $user_id = $this->Session->read('User.id'); $this->Field->hasAndBelongsToMany['User']['conditions'] = array( 'User.id' => $user_id ); }`Which is really odd, since I was trying all kinds of things to get it to run. Before this, I think maybe I was overwriting the entire array with the values from the initial declaration--it seems these get modified by cake sometime between __construct and beforeFilter. Anyway, sorry to bother you. Thanks for talking me through it.
GTT