I have forgotten more than I'll ever know
Posts tagged CakePHP
Limit results seen by users
Feb 8th
Here are a couple of nifty functions I came across, to limit the results that are returned in a Cake app.
When using the find() function, by default it will return all of the results. These two methods if placed in the appModel will only return results that are associated with a given user.
<?php function findMy($type, $options=array()) { if($this->hasField('user_id') && !empty($_SESSION['Auth']['User']['id'])){ $options['conditions'][$this->alias.'.user_id'] = $_SESSION['Auth']['User']['id']; return parent::find($type, $options); } else{ return parent::find($type, $options); } } function deleteMy($id = null, $cascade = true){ if (!empty($id)) { $this->id = $id; } $id = $this->id; if($this->hasField('user_id') && !empty($_SESSION['Auth']['User']['id'])){ $opt = array( 'conditions' => array( $this->alias.'.user_id' => $_SESSION['Auth']['User']['id'], $this->alias.'.id' => $id, ), ); if($this->find('count', $opt) > 0){ return parent::delete($id, $cascade); } } return false } ?>
Accessing user_id in CakePHP
Feb 8th
Add this to the model
class Foo extends AppModel { var $currentUsrId = NULL; }
Then add this to the controller
class FooController extends AppController { function beforeFilter(){ parent::beforeFilter(); $this->Foo->;currentUsrId = $this->;Auth->user('id'); } }