cakephp find all and afterFind method - cakephp

I have a model that has a belongsTo variable, find and a afterFind all in play. The problem is, when the afterFind is commented out find works fine, but once its in play the find only returns "true", not an array of objects. If anyone has ran into this issue please inform me thx!
Model:
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'ContactCategory' => array(
'className' => 'ContactCategory',
'foreignKey' => 'contact_category_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'State' => array(
'className' => 'State',
'foreignKey' => 'state_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public function getContact($id)
{
if ($id) {
$contact = $this->find('first', array('conditions' => array('Contact.id' => $id), 'fields' => array('id', 'image')));
return $contact;
} else {
return false;
}
}
public function afterFind($results = array(), $primary = false)
{
foreach ($results as $key => &$val) {
if (isset($val['Contact'])) {
$this->decryptFields($val['Contact'], $this->fieldsToEncrypt());
}
}
}

Related

CakeDc User $hasMany not returning Associated model

I am using the CakeDc Users plugin 2.0 and on the plugins admin_index view I would like to see the associated Books for the users.
I have added $hasMany to User.php Model
public $hasMany = array(
'Book' => array(
'className' => 'Book',
'foreignKey' => 'user_id',
'dependent' => true,
'conditions' => '',
'fields' => '',
'order' => 'order',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
And in the UserController.php I added 'contain'
protected function _setupAdminPagination() {
$this->Paginator->settings = array(
'limit' => 20,
'order' => array(
$this->modelClass . '.created' => 'desc'),
'contain' => array('Book')
);
}
public function admin_index() {
$this->Prg->commonProcess();
unset($this->{$this->modelClass}->validate['username']);
unset($this->{$this->modelClass}->validate['email']);
$this->{$this->modelClass}->data[$this->modelClass] = $this->passedArgs;
if ($this->{$this->modelClass}->Behaviors->loaded('Searchable')) {
$parsedConditions = $this->{$this->modelClass}->parseCriteria($this->passedArgs);
} else {
$parsedConditions = array();
}
$this->_setupAdminPagination();
$this->Paginator->settings[$this->modelClass]['conditions'] = $parsedConditions;
$this->set('usersList', $this->Paginator->paginate());
$this->layout = 'btst';
}
However I do not get the associated books in the view, I still just the array of users. This should work?
UPDATE:
debug ($this->Paginator->settings);
Output
array(
'limit' => (int) 20,
'order' => array(
'User.created' => 'desc'
),
'contain' => array(
(int) 0 => 'Book'
),
'User' => array(
'conditions' => array()
)
)
Debug $this->Paginator->settings before calling $this->Paginator and try
'contain' => array('Book')
However it is bad practice to modify plugins directly, you won't be able to update them anymore without trouble (merge conflicts, API changes...) in the worst case. The plugins documentation comes with a lot documentation that explains how to extend the plugin instead of modinfy it directly.
Edit: This was actually a bug in the plugin, fixed it in https://github.com/cakedc/users/commit/73aa350

Couldn't find Aco node identified by "Array ( [Aco0.model] => model [Aco0.foreign_key] => U ) "

I'm going through the following links to use Acl component in my application
http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html
http://code.tutsplus.com/tutorials/how-to-use-cakephps-access-control-lists--net-1345
in usersController i have a function to install aros and acos
public function install(){
$aro = $this->Acl->Aro;
$aco = $this->Acl->Aco;
$aro_groups = array(
0 => array(
'alias' => 'admin'
),
1 => array(
'alias' => 'operator'
),
2 => array(
'alias' => 'user'
),
);
$aco_groups = array(
0 => array(
'alias' => 'User'
),
1 => array(
'alias' => 'Supplier'
),
2 => array(
'alias' => 'Inventory'
),
3 => array(
'alias' => 'Invoice'
),
4 => array(
'alias' => 'Incentive'
),
5 => array(
'alias' => 'Promotion'
),
6 => array(
'alias' => 'Feedback'
),
7 => array(
'alias' => 'Message'
),
8 => array(
'alias' => 'History'
),
);
foreach($aro_groups as $data):
$aro->create();
$aro->save($data);
endforeach;
foreach($aco_groups as $data):
$aco->create();
$aco->save($data);
endforeach;
foreach($aco_groups as $data):
$this->Acl->allow('admin',$data);
$this->Acl->allow('operator',$data);
endforeach;
}
my user model is as follows:
public $belongsTo = array(
'Role' => array(
'className' => 'Role',
'foreignKey' => 'role_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public function beforeSave($options = array()){
if(isset($this->data['User']['password']))
{
$this->data['User']['password']= AuthComponent::password($this->data['User']['password']);
}
}
public $actsAs = array('Acl' => array('type' => 'requester'));
public function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data['User']['group_id'])) {
$groupId = $this->data['User']['group_id'];
} else {
$groupId = $this->field('group_id');
}
if (!$groupId) {
return null;
} else {
return array('Group' => array('id' => $groupId));
}
}
public function bindNode($user) {
return array('model' => 'Role', 'foreign_key' => $user['User']['role_id']);
}
role model:
public $hasMany = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'role_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
public $actsAs = array('Acl' => array('type' => 'requester'));
public function parentNode() {
return null;
}
now, when I try to access /users/install just to check that all relations are successfully created or not, i'm getting this error
AclNode::node() - Couldn't find Aco node identified by "Array ( [Aco0.model] => model [Aco0.foreign_key] => U ) "
Warning (2): Illegal string offset 'id' [CORE\Cake\Model\AclNode.php, line 140]
In the parentNode function in your User model, you have group_id instead of role_id.
Replace all occurrences of group_id to role_id in your User model and you should be ok and also Replace Group with Role
public function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data['User']['role_id'])) {
$roleId = $this->data['User']['role_id'];
} else {
$roleId = $this->field('role_id');
}
if (!$roleId) {
return null;
} else {
return array('Role' => array('id' => $roleId));
}
}

CakePHP saving data in HABTM fields

I am using these three relations User, Movie and UsersWatchlist.. Where users_watchlists contains movie_id and user_id as attributes.. I have this structure
array(
'User' => array(
'id' => '3'
),
'UsersWatchlist' => array(
'UsersWatchlist' => array(
(int) 0 => '3'
)
)
)
public function watchlist($id = null) {
$userid = '3';
if (!$id && $userid != 3) {
$this->Session->setFlash('Invalid Movie');
$this->redirect($this->referer(array('action' => 'listing')));
}
$this->request->data['User']['User'][] = $userid;
$this->request->data['Movie']['Movie'][] = $id;
debug($this->request->data);
if ($this->User->saveAll($this->request->data)) {
debug("saved");
$this->Session->setFlash('The movie has been added to your watchlist', 'admin/flash_success');
//$this->redirect($this->referer(array('action' => 'listing')));
} else {
debug("saved bo");
$this->Session->setFlash('The movie could not be added to your watchlist. Please, try again.', 'admin/flash_error');
//$this->redirect($this->referer(array('action' => 'listing')));
}
}
I used saveAll method on User but its not saving.. Please provide me solution to save the data..
In Movie model,
public $hasAndBelongsToMany = array('User' => array(
'className' => 'User',
'joinTable' => 'users_watchlists',
'foreignKey' => 'movie_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
In User model,
public $hasAndBelongsToMany = array(
'Movie' => array(
'className' => 'Movie',
'joinTable' => 'users_watchlists',
'foreignKey' => 'user_id',
'associationForeignKey' => 'movie_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
In UsersWatchlist model,
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Movie' => array(
'className' => 'Movie',
'foreignKey' => 'movie_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
The data array you're trying to save is wrong.
If you're saving throung the User model your structure should be:
array(
'User' => array(
'id' => '3'
),
'Movie' => array(
'Movie' => array(
(int) 0 => '3'
)
)

CakePHP 2.1 saving HABTM fields

I have two models User and Movie.. Where those are associated with UsersWatchlist..
public $hasAndBelongsToMany = array('User' => array(
'className' => 'User',
'joinTable' => 'users_watchlists',
'foreignKey' => 'movie_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
))
public $hasAndBelongsToMany = array(
'Movie' => array(
'className' => 'Movie',
'joinTable' => 'users_watchlists',
'foreignKey' => 'user_id',
'associationForeignKey' => 'movie_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
))
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Movie' => array(
'className' => 'Movie',
'foreignKey' => 'movie_id',
'conditions' => '',
'fields' => '',
'order' => ''
))
I created 'watchlist' action in UsersController.. The code is below
public function watchlist($id = null) {
$userid = 3;
if (!$id && $userid != 3) {
$this->Session->setFlash('Invalid Movie');
$this->redirect($this->referer(array('action' => 'listing')));
}
$this->request->data['User']['id'] = $userid;
$this->User->UsersWatchlist->create();
debug($this->User->UsersWatchlist->saveAll(array('user_id' => '2', 'movie_id' => 3)));
if ($this->User->UsersWatchlist->saveAll($this->request->data)) {
$this->Session->setFlash('The movie has been added to your watchlist', 'admin/flash_success');
$this->redirect($this->referer(array('action' => 'listing')));
} else {
$this->Session->setFlash('The movie could not be added to your watchlist. Please, try again.', 'admin/flash_error');
$this->redirect($this->referer(array('action' => 'listing')));
}
}
So i am getting an error while saving.. Please tell me the solution
Firstly your data should look like this (provided you want to save it through the user Model):
$this->request->data = array(
'User' => array(
'id' => '2',
),
'Movie' => array(
'Movie' => array(
(int) 0 => '3',
),
),
);
The main mistake I see is that you're trying to save through the Join Model, where you should be saving through the User model. So in the controller use:
$this->User->saveAll($this->request->data)
If the data is as described above it should go fine. I thought I've answered your question here.
Hope this helps.
Cheers!
Your associations seem interesting. Is there a reason you've associated the HABTM join model with the two models (user, movie)? You can achieve the same effect by putting the first $HABTM in the Movie model, and the second $HABTM in the User model. You don't need to create the intermediate join model, cake will do that for you, you only need the table.

Cake php default bahaviour for Translate behaviour not working

Can anyone suggest me why when there are no translation for a field it is returned empty, and not with the default translation?
I will appreciate all suggestions...
Can`t tell what part of my code you want to see, because it is all straight forward from www.book.cake.org. So i pasting some code:
Model definition:
<?php
class Article extends AppModel
{
var $useTable = 'nc_articles';
var $name = 'Article';
var $actsAs = array(
'Translate' => array(
'title', 'content', 'meta_key_words','meta_description'
)
);
// Use a different model
var $translateModel = 'ArticlesI18n';
// Use a different table for translateModel
var $translateTable = 'nc_articles_i18ns';
var $belongsTo = array(
'Author' => array('className' => 'User',
'foreignKey' => 'author_id',
'conditions' => '',
'fields' => array(),
'order' => '',
'counterCache' => ''),
'Modifier' => array('className' => 'User',
'foreignKey' => 'modifier_id',
'conditions' => '',
'fields' => array(),
'order' => '',
'counterCache' => ''),
'Category' => array('className' => 'ArticlesCategory',
'foreignKey' => 'category_id',
'conditions' => '',
'fields' => array(),
'order' => '',
'counterCache' => ''),
'Layout' => array('className' => 'Layout',
'foreignKey' => 'layout_id',
'conditions' => '',
'fields' => array(),
'order' => '',
'counterCache' => ''),
);
var $hasMany = array(
'Comments' => array(
'className' => 'ArticlesComment',
'foreignKey' => 'article_id',
'conditions' => array(),
'order' => '',
'limit' => '',
//'dependent'=> true When dependent is set to true, recursive model deletion is possible. In this example, Comment records will be deleted when their associated User record has been deleted.
)
);
}
?>
And then the function where I am changing Language:
function setLanguage($languageCode='pol')
{
$this->Session->write('Config.language', $languageCode);
$this->redirect($this->referer());
}
Would you like to see something more?
Let me answer my own question. There were few more things I had to write more. First of all I had to declare my Config.language in core.php then for Every model which is translated I had to declare a local variable which is an array of language codes
$this->Article->array('en','pol');
And that's how I managed the problem. But now queries for translation are very long and I am facing an optimization problem.

Resources