Invalid argument supplied for foreach() - php

I'm working in Yii framework. In my index action I created the dataprovider in the following way
$connection=Yii::app()->db;
$user_id = Yii::app()->user->id;
$sql = 'SELECT * FROM post
LEFT JOIN comment ON post.id = comment.post_id
AND comment.user_id =:user_id
LIMIT 0 , 30 ';
$command=$connection->createCommand($sql);
$command->bindParam(':user_id', $user_id,PDO::PARAM_STR);
$rawData = $command->execute();
$dataProvider=new CArrayDataProvider($rawData, array(
'id'=>'user',
'sort'=>array(
'defaultOrder' => 'post.created',
),
'pagination'=>array(
'pageSize'=>10,
),
));
then I render the index view
$this->render('index',array(
'dataProvider'=>$dataProvider,
'category_id'=>$category_id,
));
Index view is doing
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>
which cause the error
Invalid argument supplied for foreach()
C:\wamp\www\yii\framework\web\CArrayDataProvider.php(140)
* #param array $directions the sorting directions (field name => whether it is descending sort)
*/
136 foreach($directions as $name=>$descending)
137 {
138 $column=array();
139 $fields_array=preg_split('/\.+/',$name,-1,PREG_SPLIT_NO_EMPTY);
140 foreach($this->rawData as $index=>$data)
141 $column[$index]=$this->getSortingFieldValue($data, $fields_array);
142 $args[]=&$column;
143 $dummy[]=&$column;
144 unset($column);
145 $direction=$descending ? SORT_DESC : SORT_ASC;
146 $args[]=&$direction;
147 $dummy[]=&$direction;
148 unset($direction);
149 }
Can you help me?
Thank you in advance

If you var_dump($rawData), you'll see that it's an integer (or 0) and is only returning the number of results.
This is because you're using $command->execute() when you should be using:
$command->queryAll();
That will return you an array of results which you can pass into the CActiveDataProvider

Related

Another yii - Trying to get property of non-object

sory another yii question, try this bust seems doesnt works.
I have this error, still learning yii
Trying to get property of non-object
D:\xampp\htdocs\mou\protected\views\mou\view.php(26)
Did i miss something? thanks before.
D:\xampp\htdocs\mou\protected\views\mou\view.php(26)
14 'value'=>Yii::app()->dateFormatter->format('dd/MM/yyyy',$model->tgl_perjanjian),
15 ),
16 array(
17 'name'=>'tgl_awal',
18 'value'=>Yii::app()->dateFormatter->format('dd/MM/yyyy',$model->tgl_awal),
19 ),
20 array(
21 'name'=>'tgl_akhir',
22 'value'=>Yii::app()->dateFormatter->format('dd/MM/yyyy',$model->tgl_akhir),
23 ),
24 array(
25 'name'=>'Mitra KY',
26 'value'=>$model->mitra_mous->mitra->nama,
27 ),
28 'lingkup_kerjasama',
29 'penandatangan',
30 'jabatan_penandatangan',
31 array(
32 'name'=>'file',
33 'type'=>'raw',
34 'value'=>CHtml::link($model->file,Yii::app()->baseUrl . '/files/mou/' .$model->file),
35 ),
36 ),
37 )); ?>
this is my models Mitra.php
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'jenis0' => array(self::BELONGS_TO, 'JenisMitra', 'jenis'),
'kab0' => array(self::BELONGS_TO, 'Wilayah', 'kab'),
'prov0' => array(self::BELONGS_TO, 'Wilayah', 'prov'),
'mitra_mous' => array(self::HAS_MANY, 'MitraMou', 'mitra_id'),
);
}
and this is models Mou.php
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'mitra_mous' => array(self::HAS_MANY, 'MitraMou', 'mou_id'),
'mitras' => array(self::HAS_MANY, 'Mitra', 'mitra_id','through'=>'mitra_mous'),
);
}
Change your line 26 to the code below.
use this code below
'value'=>$model->mitras->nama,
It seems that your mitra_mous relation is the problem. Due to the fact that the relation is a one-to-many relation, $model->mitra_mous will return an array. You cannot try to get a property from an array, so $model->mitra_mous->mitra is invalid. Maybe you can reference only one of the items of the array, say $model->mitra_mous[0]->mitra->nama.
I am not sure if this solves your issue, but at least that line should work.
Be careful with this solution anyway, because if $model->mitra_mous has no elements, the code will fail. Yo may have to add a condition for that case.
Hope I have helped.
Good luck!

yii join table using relations deploy to Linux not work

I using curd to show CGridview I join 2 table in my computer it work
but when deploy to linux server not work what wrong? ,help me pls!!
in controller
myController
$model=new UserLogin('search');
$model->unsetAttributes();
$dataProvider = new CActiveDataProvider('UserLogin', array(
'criteria' => array(
'with'=>'group',
),
'pagination' => array(
'pageSize' => 20,
),
));
$this->render('admin', array(
'dataProvider'=>$dataProvider,'model'=>$model)
);
this error
Invalid argument supplied for foreach()
/data/home/nueng/www/html/framework/db/ar/CActiveFinder.php(466)
454
455 /**
456 * Performs lazy find with the specified base record.
457 * #param CActiveRecord $baseRecord the active record whose related object is to be fetched.
458 */
459 public function lazyFind($baseRecord)
460 {
461 if(is_string($this->_table->primaryKey))
462 $this->records[$baseRecord->{$this->_table->primaryKey}]=$baseRecord;
463 else
464 {
465 $pk=array();
466 foreach($this->_table->primaryKey as $name)
467 $pk[$name]=$baseRecord->$name;
468 $this->records[serialize($pk)]=$baseRecord;
469 }
470
Hum just a guess are you respecting the case in the model name group in your with criteria?
Linux is case sensitive so if you put group instead of Group in your relation name or in the model name of the relation an error could occur.

Yii CGridView Model Set Default Sorting Order [duplicate]

This question already has an answer here:
Yii Set Default Sort Order in Model
(1 answer)
Closed 9 years ago.
My Yii CGridView Sorting is not working this way when
public function search() {
$criteria = new CDbCriteria;
$criteria->order = "member_id DESC";
When I click header menu in CGridView it is not working but when I remove
$criteria->order = "member_id DESC";`
sorting is working fine. I want to show records by default order by member_id desc.
Remove this line $criteria->order = "member_id DESC";
Amend your return:
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'sort' => array(
'defaultOrder' => 'member_id DESC',
),
));
Use CActiveDataProvider: In this class CActiveDataProvider you can find the property defaultOrder to set the defult visible order in your grid view with respect to your database table column name.
defaultOrder: defaultOrder is a property in CActiveDataProvider class. This property is belongs to the class CSort. As the class CActiveDataProvider inherited CSort, defaultOrder property became a property of CActiveDataProvider.
The syntax to do your task is
$dataProvider = new CActiveDataProvider('YourModel',
array(
'sort' => array('defaultOrder' => 'member_id DESC')
));
Pass this $dataProvider to your view
$this->render('YourView', array(
'dataProvider' => $dataProvider
));
As you want to presenting the results in CGridView
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'data-grid',
'dataProvider' => $model->search(),
'columns' => array(
'column1',
'column2',
'column3',
array('class' => 'CButtonColumn'),
),
));
I think problem is here
$criteria->order = "member_id DESC";
Just Remove this line and then add in
return new CActiveDataProvider($this,array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'member_id DESC',
),
));
hope it will be help you.

PHP export to excel using eexcelview

Hi I'm trying to get data in excel with eexcelview . I have added the code in controller
$query = " some query from 4 tables ";
$dataProvider=new CSqlDataProvider($query, array(
'sort'=>array('attributes'=>array(
'col1',
'col2',
'col3',
'col4',
'col5' ),),));
$this->widget('application.extensions.EExcelView', array(
'dataProvider'=> $dataprovider,
'title'=>'Title',
'autoWidth'=>false,
));
My understanding is when this action is called, it will directly ask me to save excel report. But instead I'm getting error The "dataProvider" property cannot be empty.,
C:\wamp\www\yii\framework\zii\widgets\CBaseListView.php(106)
100 * Initializes the view.
101 * This method will initialize required property values and instantiate {#link columns} objects.
102 */
103 public function init()
104 {
105 if($this->dataProvider===null)
106 throw new CException(Yii::t('zii','The "dataProvider" property cannot be empty.'));
Also, same $dataprovider in CGridView works fine.
What is wrong in my code ?
PHP variables are case sensitive. So you must change your code to
$this->widget('application.extensions.EExcelView', array(
'dataProvider'=> $dataProvider,
'title'=>'Title',
'autoWidth'=>false,
));

CActiveDataProvider not resolving params in criteria

I'm following along with Agile Web Application Development with Yii 1.1 and PHP5, working on the "TrackStar" project. For the life of me I can't understand where my problem is.
I'm getting the Exception:
CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined. The SQL statement executed was: SELECT COUNT(*) FROM tbl_issue t WHERE project_id=:projectId
It appears (to this noob's interpretation) that the params in my CActiveDataProvider is some how not resolving in the criteria as in the view:
(in /protected/controllers/ProjectController.php)
55 public function actionView()
56 {
57 $issueDataProvider = new CActiveDataProvider('Issue', array(
58 'criteria' => array(
59 'condition' => 'project_id=:projectId',
60 'params' => array(':projectId=' => $this->loadModel()->id),
61 ),
62 'pagination' => array(
63 'pageSize' => 1,
64 ),
65 ));
66 $this->render('view',array(
67 'model'=>$this->loadModel(),
68 'issueDataProvider' => $issueDataProvider,
69 ));
70 }
I checked my code against a github repo and I couldn't find any differences anywhere.
Is there something straightforward I'm missing here without having to post all of my code (and have somebody actually look through it)?
It looks you have an error in params of your criteria. (= after :projectId).
Right statement is
'params' => array(':projectId' => $this->loadModel()->id),
Params array is list of query parameter values indexed by parameter placeholders. For example, array(':name'=>'Dan', ':age'=>'31').

Categories