I'm new to CakePHP and just want to display a list of associated tags in a post's view.
I have searched all over the web and nothing seems to work.
This is what I have at the moment:
// PostController
public function view($id = null) {
$this->set('tags', $this->Post->Tag->find('all', array('conditions' => array('PostTag.post_id' => $id))));
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
// Post's view.ctp
echo $this->Text->toList($tags);
This is the error I'm getting:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'PostTag.post_id' in 'where clause'
This should be so easy but I am completely stuck.
Thanks to anyone who can help!
Is the Tag model loaded in your Post controller? How about simply:
$this->set('tags', $this->Tag->find('all', array('conditions' => array('Tag.post_id' => $id))));
Finally! After finding another question here about joining tables and some experimentation, I got it to work.
public function view($id = null) {
$options = array(
'joins' => array(
array('table' => 'posts_tags',
'alias' => 'PostTags',
'type' => 'left',
'conditions' => array(
'Post.id = PostTags.post_id'
)
),
array('table' => 'tags',
'alias' => 'Tag',
'type' => 'left',
'conditions' => array(
'PostTags.tag_id = Tag.id'
)
)
)
,'conditions' => array(
'PostTags.post_id' => $id
)
,'fields' => array(
'Tag.title' // the name of the tag
)
,'recursive' => -1
);
$tagsList = $this->Post->find('all', $options);
// added $result and foreach to ensure that all results would be printed
$result = array();
foreach ($tagsList as $tag):
array_push($result, $tag['Tag']['title']);
endforeach;
$this->set('tags', $result);
// ... rest of the call to find the post info
}
// Post's view.ctp
echo $this->Text->toList($tags);
Before I added $result, it would only print out the first association. I used "echo pr($tags);" in my view and found that the results I wanted were nested inside two arrays. After I added the foreach, it would correctly list all of the assigned tags in my view.
Related
I have simple Yii cgridview code with pagination. Pagination is working fine but in the last page I have faced one issue.
For example, If I have 13 records in DB table, and set pagination for 10 pages per page then for first page It will show "1 - 10 of 13 results" but when I clicked on 2nd page link then It will show "4 - 13 of 13" instead of "11 - 13 of 13".
Here is my code.
1) Controller :
function actiontransactionHistory(){
$creditTransactionObj = new CreditTransaction();
$this->render('history',array(
'creditTransactionObj'=>$creditTransactionObj,
));
}
2) Model :
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id,true);
$criteria->compare('fkasmtGroupId',$this->fkasmtGroupId);
$criteria->compare('fkgroupSurveyUserId',$this->fkgroupSurveyUserId,true);
$criteria->compare('fkasmtId',$this->fkasmtId);
$criteria->compare('transaction_type',$this->transaction_type);
$criteria->compare('credit_type',$this->credit_type,true);
$criteria->compare('credit_qty',$this->credit_qty);
$criteria->compare('transaction_date',$this->transaction_date,true);
$criteria->compare('isDelete',$this->isDelete);
$criteria->compare('status',$this->status);
$criteria->compare('created_at',$this->created_at,true);
$criteria->compare('modified_at',$this->modified_at,true);
$sort = array(
"defaultOrder" => "transaction_date DESC",
);
return new CActiveDataProvider($this, array(
"criteria"=>$criteria,
"sort" => $sort,
));
}
3) View:
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'history-grid',
'dataProvider' => $creditTransactionObj->search(),
'loadingCssClass' => '',
'enableSorting' => true,
'itemsCssClass' => 'my-teams',
'summaryText' => "Displaying {start} - {end} of {count} results.",
"emptyText" => "There is no transaction history available.",
'columns' => array(
array('name' => 'transaction_date', 'header' => 'Date', 'type' => 'raw', 'value' => 'date("d-M-Y",strtotime($data->transaction_date))', 'htmlOptions' => array('class' => '')),
array('name' => 'credit_qty', 'header' => '# of Credits', 'sortable'=>false, 'type' => 'raw', 'value' => '($data->transaction_type == 1) ? - $data->credit_qty : $data->credit_qty', 'htmlOptions' => array('class' => '')),
array('name' => 'credit_type', 'header' => 'Type', 'type' => 'raw', 'value' => '$data->credit_type', 'htmlOptions' => array('class' => '')),
array('name' => 'transaction_type', 'header' => 'Activity', 'type' => 'raw', 'value' => '($data->transaction_type == 0) ? "Purchased" : (($data->transaction_type == 1) ? "Spent" : "Refunded")', 'htmlOptions' => array('class' => '')),
array('name' => 'fkasmtGroupId', 'header' => 'Group Name', 'type' => 'raw', 'value' => array($this,'getGroupName'), 'htmlOptions' => array('width' => '35%')),
)
));
?>
I have also attached both pages screenshot.
Any help will be appreciate. Thanks in advance !
After spending lots of hours finally I found the solution for this issue.
Actually the problem was in fetchData() function which is used in
yii/framework/web/CActiveDataProvider.php framework class file.
In fetchData() method, limit was not calculated properly for the last page pagination. so I have made changes to calculate correct limit.
Old Code:
protected function fetchData()
{
$criteria=clone $this->getCriteria();
if(($pagination=$this->getPagination())!==false)
{
$pagination->setItemCount($this->getTotalItemCount());
$pagination->applyLimit($criteria);
}
$baseCriteria=$this->model->getDbCriteria(false);
if(($sort=$this->getSort())!==false)
{
// set model criteria so that CSort can use its table alias setting
if($baseCriteria!==null)
{
$c=clone $baseCriteria;
$c->mergeWith($criteria);
$this->model->setDbCriteria($c);
}
else
$this->model->setDbCriteria($criteria);
$sort->applyOrder($criteria);
}
$this->model->setDbCriteria($baseCriteria!==null ? clone $baseCriteria : null);
$data=$this->model->findAll($criteria);
$this->model->setDbCriteria($baseCriteria); // restore original criteria
return $data;
}
New Code:
protected function fetchData()
{
$criteria=clone $this->getCriteria();
if(($pagination=$this->getPagination())!==false)
{
$pagination->setItemCount($this->getTotalItemCount());
$pagination->applyLimit($criteria);
// update limit to the correct value for the last page
$limit=$pagination->getLimit();
$offset=$pagination->getOffset();
if ( $offset+$limit > $pagination->getItemCount() )
$criteria->limit = $pagination->getItemCount() - $offset;
}
$baseCriteria=$this->model->getDbCriteria(false);
if(($sort=$this->getSort())!==false)
{
// set model criteria so that CSort can use its table alias setting
if($baseCriteria!==null)
{
$c=clone $baseCriteria;
$c->mergeWith($criteria);
$this->model->setDbCriteria($c);
}
else
$this->model->setDbCriteria($criteria);
$sort->applyOrder($criteria);
}
$this->model->setDbCriteria($baseCriteria!==null ? clone $baseCriteria : null);
$data=$this->model->findAll($criteria);
$this->model->setDbCriteria($baseCriteria); // restore original criteria
return $data;
}
But remember, never update a core class file of framework. so I just extend this method in my Model file and write below code.
Final Code In My Model file without change in framework file:
class CustomActiveDataProvider extends CActiveDataProvider
{
/**
* Fetches the data from the persistent data storage.
* #return array list of data items
*/
protected function fetchData()
{
$criteria=clone $this->getCriteria();
if(($pagination=$this->getPagination())!==false)
{
$pagination->setItemCount($this->getTotalItemCount());
$pagination->applyLimit($criteria);
// update limit to the correct value for the last page
$limit=$pagination->getLimit();
$offset=$pagination->getOffset();
if ( $offset+$limit > $pagination->getItemCount() )
$criteria->limit = $pagination->getItemCount() - $offset;
}
$baseCriteria=$this->model->getDbCriteria(false);
if(($sort=$this->getSort())!==false)
{
// set model criteria so that CSort can use its table alias setting
if($baseCriteria!==null)
{
$c=clone $baseCriteria;
$c->mergeWith($criteria);
$this->model->setDbCriteria($c);
}
else
$this->model->setDbCriteria($criteria);
$sort->applyOrder($criteria);
}
$this->model->setDbCriteria($baseCriteria!==null ? clone $baseCriteria : null);
$data=$this->model->findAll($criteria);
$this->model->setDbCriteria($baseCriteria); // restore original criteria
return $data;
}
}
// Used this custome active data provider as shown in below.
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id,true);
$criteria->compare('isDelete',$this->isDelete);
$criteria->compare('status',$this->status);
$criteria->compare('created_at',$this->created_at,true);
$criteria->compare('modified_at',$this->modified_at,true);
$sort = array(
"defaultOrder" => "transaction_date DESC",
);
return new CustomActiveDataProvider($this, array(
"criteria"=>$criteria,
"sort" => $sort,
"pagination" => array('pageSize' => (isset($_REQUEST['pageSize'])?$_REQUEST['pageSize']:10))
));
}
After this change, Last page pagination works completely fine.
Thanks!
In my GridView I want to display all records of my table 'reply'. The table has relations to the tables 'author' and 'task' and not every reply has a task.
The table 'task' has a relation with another table called 'concern'.
Here ist the relations() of my model Reply:
public function relations() {
return array(
'trak' => array(self::HAS_MANY, 'Task', 'reply_id', 'condition' => 'task.deleted<>1'),
'author' => array(self::BELONGS_TO, 'Author', 'author_id'),
);
}
The search() method of my model Reply has the following code:
public function search() {
$criteria = new CDbCriteria;
$criteria->with = array(
'author' => array('select' => 'id, name, role, office_id, abk', 'together' => false),
'author.office' => array('select' => 'id, name'),
'task' => array('select' => 'id, concern_id', 'together' => true),
'task.concern' => array('select' => 'id, classification_id', 'alias' => 'concern'),
);
$criteria->compare('t.id', $this->id);
$criteria->compare('t.create_time', $this->create_time);
$criteria->compare('t.create_date', $this->create_date, true);
$criteria->compare('t.office.id', $this->search_office);
$criteria->compare('t.author_id', $this->author_id);
$criteria->compare('t.rel', $this->rel, true);
$criteria->compare('t.author_id', $this->author_id);
$criteria->compare('t.lektor_id', $this->lektor_id);
$criteria->compare('t.issue_id', $this->issue_id);
$criteria->compare('t.reply_text', $this->reply_text, true);
$criteria->compare('t.deleted', $this->deleted);
if (EWMParam::getValue(EWMParam::MODUL_SCHLAGWORTE))
$criteria->compare('t.tags', $this->tags, true);
$criteria->compare('t.text_name', $this->text_name, true);
$criteria->compare('t.use_count', $this->use_count);
$criteria->compare('concern.classification_id', $this->classification_id);
$criteria->compare('t.update_time', $this->update_time);
$criteria->compare('t.update_user', $this->update_user);
$criteria->compare('t.global', $this->global);
if (EWMParam::getValue(EWMParam::MODUL_confirmationN))
$criteria->compare('t.confirmation', $this->confirmation);
$criteria->compare('t.confirmation_text', $this->confirmation_text, true);
$criteria->compare('t.use', $this->use, true);
$pagination = EWMPageSortFilterHelper::getPagination($this);
$sort = new CSort();
$sort->defaultOrder = 't.id DESC';
$sort->attributes = array(
'global' => 't.global',
'search_office' => 'office.name',
'id' => 't.id',
'text_name' => 't.text_name',
'confirmation' => 't.confirmation',
'author_id' => 'author.name',
'create_date' => 't.create_date',
'tags' => 't.tags',
'use' => 't.use',
'classification_id' => 'classification_id',
);
$sort->applyOrder($criteria);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => $pagination,
'sort' => $sort
));
}
In my GridVew only replys with a task are displayed and all filters work fine. But I want to display all replys with a task and all replys without a task. If I
delete in the search() method in the array for $criteria->with the elements 'task' and 'task.concern' all replys are displyed. But the filter for the row
'Classifcation' which comes from the relation 'task.concern' doesn't work. Logically I get the error "Column not found: 1054 Unknown column 'concern.classification_id' in 'where clause'".
Is it possible to display all replys and to filter those replys by the classification? Do you have an idea?
You should look into how Yii relations work.
One thing that comes into my mind is that when adding the relations in the with() property the SQL generated might include INNER JOINs.
That's why when having the relations included you're not getting any reply without tasks.
In order to fix that you should make sure that the SQL generated is using LEFT JOINs.
You can do that by using joinType property of a relation:
http://www.yiiframework.com/doc/api/1.1/CActiveRelation#joinType-detail
And you could specify LEFT JOIN there.
'task' => array('select' => 'id, concern_id', 'together' => true, 'joinType'=>'LEFT JOIN'),
'task.concern' => array('select' => 'id, classification_id', 'alias' => 'concern', 'together' => true, 'joinType'=>'LEFT JOIN'),
That might do the trick. But maybe you need some more tweaking if it is not working just as expected.
If you want to debug what is actually happening, you could put a bad field/table name inside the criteria that would result in a database error and then you can look in the SQL code that was executed and see how tables are joined.
Suggested links:
http://www.yiiframework.com/doc/guide/1.1/en/database.arr
http://www.yiiframework.com/wiki/527/relational-query-lazy-loading-and-eager-loading-with-and-together/
http://www.yiiframework.com/wiki/428/drills-search-by-a-has_many-relation
I am trying to take advantage of CakePHP's saveMany feature (with associated data feature), however am creating duplicate records. I think it is because the find() query is not finding authors, as the transaction has not yet been committed to the database.
This means that if there are two authors with the same username, for example, in the spreadsheet, then CakePHP will not associate the second with the first, but rather create two. I have made up some code for this post:
/*
* Foobar user (not in database) entered twice, whereas Existing user
* (in database) is associated
*/
$spreadsheet_rows = array(
array(
'title' => 'New post',
'author_username' => 'foobar',
'content' => 'New post'
),
array(
'title' => 'Another new post',
'author_username' => 'foobar',
'content' => 'Another new post'
),
array(
'title' => 'Third post',
'author_username' => 'Existing user',
'content' => 'Third post'
),
array(
'title' => 'Fourth post', // author_id in this case would be NULL
'content' => 'Third post'
),
);
$posts = array();
foreach ($spreadsheet_rows as $row) {
/*
* This query doesn't pick up the authors
* entered automatically (see comment 2.)
* within the db transaction by CakePHP,
* so creates duplicate author names
*/
$author = $this->Author->find('first', array('conditions' => array('Author.username' => $row['author_username'])));
$post = array(
'title' => $row['title'],
'content' => $row['content'],
);
/*
* Associate post to existing author
*/
if (!empty($author)) {
$post['author_id'] = $author['Author']['id'];
} else {
/*
* 2. CakePHP creates and automatically
* associates new author record if author_username is not blank
* (author_id is NULL in db if blank)
*/
if (!empty($ow['author_username'])) {
$post['Author']['username'] = $row['author_username'];
}
}
$posts[] = $post;
}
$this->Post->saveMany($posts, array('deep' => true));
Is there any way that this can be achieved, while also keeping transactions?
Update
You new requirement to save also posts that have no associated authors changes the situation a lot, as mentioned in the comments, CakePHPs model save methods are not ment to be able to save data from different models at once if it's not an association, if you need to do this in a transaction, then you'll need to handle this manually.
Save authors and their posts instead of posts and their authors
I would suggest that you save the data the other way around, that is save authors and their associated posts, that way you can easily take care of the duplicate users by simply grouping their data by using the username.
That way around CakePHP will create new authors only when neccessary, and add the appropriate foreign keys to the posts automatically.
The data should then be formatted like this:
Array
(
[0] => Array
(
[username] => foobar
[Post] => Array
(
[0] => Array
(
[title] => New post
)
[1] => Array
(
[title] => Another new post
)
)
)
[1] => Array
(
[id] => 1
[Post] => Array
(
[0] => Array
(
[title] => Third post
)
)
)
)
And you would save via the Author model:
$this->Author->saveMany($data, array('deep' => true));
Store non associated posts separately and make use of transactions manually
There is no way around this if you want to use the CakePHP ORM, just imagine what the raw SQL query would need to look like if it would need to handle all that logic.
So just split this into two saves, and use DboSource::begin()/commit()/rollback() manually to wrap it all up.
An example
Here's a simple example based on your data, updated for your new requirements:
$spreadsheet_rows = array(
array(
'title' => 'New post',
'author_username' => 'foobar',
'content' => 'New post'
),
array(
'title' => 'Another new post',
'author_username' => 'foobar',
'content' => 'Another new post'
),
array(
'title' => 'Third post',
'author_username' => 'Existing user',
'content' => 'Third post'
),
array(
'title' => 'Fourth post',
'content' => 'Fourth post'
),
array(
'title' => 'Fifth post',
'content' => 'Fifth post'
),
);
$authors = array();
$posts = array();
foreach ($spreadsheet_rows as $row) {
// store non-author associated posts separately
if (!isset($row['author_username'])) {
$posts[] = $row;
} else {
$username = $row['author_username'];
// prepare an author only once per username
if (!isset($authors[$username])) {
$author = $this->Author->find('first', array(
'conditions' => array(
'Author.username' => $row['author_username']
)
));
// if the author already exists use its id, otherwise
// use the username so that a new author is being created
if (!empty($author)) {
$authors[$username] = array(
'id' => $author['Author']['id']
);
} else {
$authors[$username] = array(
'username' => $username
);
}
$authors[$username]['Post'] = array();
}
// group posts under their respective authors
$authors[$username]['Post'][] = array(
'title' => $row['title'],
'content' => $row['content'],
);
}
}
// convert the string (username) indices into numeric ones
$authors = Hash::extract($authors, '{s}');
// manually wrap both saves in a transaction.
//
// might require additional table locking as
// CakePHP issues SELECT queries in between.
//
// also this example requires both tables to use
// the default connection
$ds = ConnectionManager::getDataSource('default');
$ds->begin();
try {
$result =
$this->Author->saveMany($authors, array('deep' => true)) &&
$this->Post->saveMany($posts);
if ($result && $ds->commit() !== false) {
// success, yay
} else {
// failure, buhu
$ds->rollback();
}
} catch(Exception $e) {
// failed hard, ouch
$ds->rollback();
throw $e;
}
You need to use saveAll, which is a mix between saveMany and saveAssociated (you will need to do both of them here).
Plus, you need to change the structure of each post.
Here is an example of the structures you will need to create inside the loop.
<?php
$posts = array();
//This is a post for a row with a new author
$post = array (
'Post' => array ('title' => 'My Title', 'content' => 'This is the content'),
'Author' => array ('username' => 'new_author')
);
$posts[] = $post;
//This is a post for a row with an existing author
$post = array (
'Post' => array ('title' => 'My Second Title', 'content' => 'This is another content'),
'Author' => array ('id' => 1)
);
$posts[] = $post;
//This is a post for a row with no author
$post = array (
'Post' => array ('title' => 'My Third Title', 'content' => 'This is one more content')
);
$posts[] = $post;
$this->Post->saveAll($posts, array ('deep' => true));
?>
Following the "use transactions manually" bit suggested by ndm, this piece of code (written in a unit test!) seemed to do the trick:
public function testAdd() {
$this->generate('Articles', array());
$this->controller->loadModel('Article');
$this->controller->loadModel('Author');
$csv_data = array(
array(
'Article' => array(
'title' => 'title'
)),
array(
'Article' => array(
'title' => 'title'
),
'Author' => array(
'name' => 'foobar'
),
),
array(
'Article' => array(
'title' => 'title2'
),
'Author' => array(
'name' => 'foobar'
)
),
/* array( */
/* 'Article' => array( */
/* 'title' => '' */
/* ), */
/* 'Author' => array( */
/* 'name' => '' // this breaks our validation */
/* ) */
/* ), */
);
$db = $this->controller->Article->getDataSource();
$db->begin();
/*
* We want to inform the user of _all_ validation messages, not one at a time
*/
$validation_errors = array();
/*
* Do this by row count, so that user can look through their CSV file
*/
$row_count = 1;
foreach ($csv_data as &$row) {
/*
* If author already exists, don't create new record, but associate to existing
*/
if (!empty($row['Author'])) {
$author = $this->controller->Author->find('first',
array(
'conditions' => array(
'name' => $row['Author']['name']
)
));
if (!empty($author)) {
$row['Author']['id'] = $author['Author']['id'];
}
}
$this->controller->Article->saveAssociated($row, array('validate' => true));
if (!empty($this->controller->Article->validationErrors)) {
$validation_errors[$row_count] = $this->controller->Article->validationErrors;
}
$row_count++;
}
if (empty($validation_errors)) {
$db->commit();
} else {
$db->rollback();
debug($validation_errors);
}
debug($this->controller->Article->find('all'));
}
I am trying create a webapplication with CakePHP. I am newbie with that but i created a lot lines of code. Now i have to add ACL and now i have a big problem. My foreach loop with if statement call $this->ACL->deny('Group', 'Alias in ARO table') or $this->ACL->allow('Group', 'Alias in ARO table'). Everything is fine and automatic table acos_aros is modified great ... BUT !! i have one alias which generate something like that:
Warning (512): DbAcl::allow() - Invalid node [CORE\Cake\Model\Permission.php, line 182]
I have no idea why. It is 'Podopieczni' when i change to 'Podopieczn' or to 'Podopieczni1' then is working fine without any errors. Anybody can told me why alias 'Podopieczni' generate that error ?
EDIT 1
My bad. I have actually problem with ACO not Aro as said before. When i change alias in ACO table from Podopieczni to Podopieczni1 or something else is working. Alias Podopieczni is generate error.
Here is my code
public function pokaz(){
if ($this->request->is('post')){
$acl['Aro'] = $this->Acl->Aro->find('list', array(
'fields' => array('id', 'alias'),
'conditions' => array(
'parent_id IS NULL'
)
));
$acl['Aco'] = $this->Acl->Aco->find('list', array(
'fields' => array('id', 'alias'),
'conditions' => array(
'parent_id IS NULL'
)
));
foreach($this->request->data['uprawnienia'] AS $pozycja => $uprawnienie){
$t_aco = $acl['Aco'][split('-',$pozycja)[0]];
$t_aro = $acl['Aro'][split('-',$pozycja)[1]];
if($uprawnienie){
//echo 'ALLOW: '.$t_aro.' => '.$t_aco.'<br>';
$this->Acl->Allow($t_aro, $t_aco);
} else {
//echo 'DENY: '.$t_aro.' => '.$t_aco.'<br>';
$this->Acl->Deny($t_aro, $t_aco);
}
}
//$this->redirect(array('controller'=>'admin', 'action' => 'pokaz'));
//$this->render('/admin/pokaz');
//exit;
}
$wynik = $this->Acl->Aco->find('all', array(
'conditions' => array(
'parent_id is null'
)
));
for($a=0; $a<count($wynik); $a++){
$tmp = array();
foreach($wynik[$a]['Aro'] AS $wiersz){
$tmp[$wiersz['foreign_key']] = $wiersz;
}
$wynik[$a]['Aro'] = $tmp;
}
$this->set('wyniki', $wynik);
$this->set('grupy', $this->requestAction('/admin/pobierzGrupy'));
}
SOLVED
In the ACOS table I have two rows with this same alias.
YOU ARE AWESOME noslone. VERY BIG THANKS FOR YOUR TIME AND PATIENCE :)))
That alias does not exist in the aros or acos table.
You should create it first.
For ARO:
$aroData = array(
'id' => NULL,
'model' => 'Group',
'alias' => 'Podopieczni'
);
$this->Acl->Aro->save($aroData);
For ACO:
$acoData = array(
'id' => NULL,
'parent_id' => NULL,//or parent_id?
'alias' => 'Podopieczni'
);
$this->Acl->Aco->save($acoData);
You should read the Documentation, it is explained pretty nice.
In my model I have this
function pieChart($conditions = null) {
//Get Data for PieChart
$this->RecordDrug->virtualFields['sum'] ='COUNT(*)';
$records = array();
$records=$this->RecordDrug->find('list',
array(
'conditions' => $conditions,
'fields' => array( 'Drug.drug', 'sum'),
'order' => array('sum' => 'desc'),
'contain' => array( 'Drug', 'Record' ),
'group' => 'Drug.Drug'
));
return $records;
}
Which basically means that when this function is called by it's self, there are no conditions set. So inside my controller, I am able to define a condition, if i'd like. I want to do the exact same thing except with
'limit' => $limit,
and I assume I need to set
$limit = null
Inside the parenthesis of the function. I've tried & and , and $limit,$conditions = null
but neither of these options worked. I am not too experience with OOP but I assume there is a way to do this?
EDIT:
Updated code, Still not working. The first varialbe that comes inside the functions parenthesis is the one that works, the second one just act's like it's not there
Model:
function pieChart($limit = null, $conditions = null) {
//Get Data for PieChart
$this->RecordDrug->virtualFields['sum'] ='COUNT(*)';
$records = array();
$records=$this->RecordDrug->find('list',
array(
'conditions' => $conditions,
'fields' => array( 'Drug.drug', 'sum','Record.unit'),
'order' => array('sum' => 'desc'),
'limit' => $limit,
'contain' => array( 'Drug', 'Record' ),
'group' => 'Drug.Drug'
));
debug($records);
return $records;
}
Controller:
$conditions = array('Record.user_id' => $this->Session->read('Auth.User.id'));
$pieChart = $this->Record->pieChart($conditions);
$this->set('output',$pieChart);
Even after this conditions variable, it does not only load the users data. If I were to remove '$limit = null' it will work as intended.
This way:
function pieChartTwo($limit = null, $conditions = null) {
...
}