Displaying value from join table in Yii CgridView - yii

I have this very simple table in my view and I'm trying to display value from joined table:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'skills-grid',
'dataProvider'=>$model->searchWithStudentSuccessRate($id),
'template' => '{items}{pager}',
'cssFile'=>Yii::app()->request->baseUrl. '/themes/'. Yii::app()->theme->name.'/css/table.css',
'htmlOptions'=>array('class'=>'datagrid', 'style'=>'width:550px;'),
'columns'=>array(
array(
'name'=>'name',
),
array(
'name' => 'value',
'header' => Yii::t('MainTrans', 'Value'),
'value' => '$data->student_skills->value',
),
array(
'name' => 'successRate',
'header' => Yii::t('MainTrans', 'Success Rate'),
'value' => '$data->successRate."%"',
),
),
));
And this is the search function:
public function searchWithStudentSuccessRate($id)
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name,true);
$criteria->compare('t.threshold',$this->threshold);
$criteria->with = array('student_skills');
$criteria->together = true;
$criteria->select = array('IFNULL(CASE WHEN ROUND((student_skills.value/t.threshold)*100,0) > 100 THEN 100 ELSE ROUND((student_skills.value/t.threshold)*100,0) END,0) as successRate','*');
$criteria->group = "t.name";
$criteria->condition = 'student_skills.student_id = '.$id;
$criteria->compare('successRate',$this->successRate);
$criteria->compare('student_skills.value',$this->value);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>25,
),
'sort'=>array(
'defaultOrder'=>array(
'successRate'=>CSort::SORT_DESC,
),
'attributes'=>array(
'successRate'=>array(
'asc'=>'successRate',
'desc'=>'successRate DESC',
),
'*',
),
),
));
}
But I get error: "Trying to get property of non-object" when I added value column to my CGridView.
Everything works fine without column value (columns successRate and name are fine). Relation should be fine as well. The error I get means that the value doesn't exist but it should since I did something similar in my other views and there it works.
Can anyone tell what's wrong? I'm sure it's something minor but I'm struggling with this embarrasing problem for a while.
Thanks

It means that in some conditions $data->student_skills is NULL. Try change this:
'value' => '$data->student_skills->value',
to this
'value' => 'empty($data->student_skills) ? null : $data->student_skills->value',

Related

Yii1 CGridView - SUM of Custom Column Value in footer

I want Sum of a custom column value in footer
GridView Code
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'booking-grid',
'dataProvider'=>$model->search(),
'columns'=>array(
array(
'name'=>'name',
'header'=>'User Name',
'value'=>'$data->booking_id',
'filter'=>false,
'footer'=>'Total',
'footerHtmlOptions'=>array('class'=>'grid-footer'),
),
array(
'name'=>'id',
'header'=>'User Fee',
'value'=> array($model,'GetUserFee'),
'filter'=>false,
'footer'=>'' . $model->getTotal($model->search()->getData(), 'id'),
'footerHtmlOptions'=>array('class'=>'grid-footer'),
),
),
));
Get Total
public function getTotal($records,$colName){
$total = 0.0;
if(count($records) > 0){
foreach ($records as $record) {
$total += $record->$colName;
}
}
return number_format($total,2);
}
Second column value are calculate user fee.
In footer sum of User Fee values get the wrong sum. It gives the sum of user ids. and id is table column name.
How can I get the sum of User fee column values
Instead of using a literal representation of id, try using the $data variable created by CGridView, which actually IS the current record from the $model currently being processed in each CGridView iteration.
Your code would then be:
array(
'name'=>'id',
'header' => 'User Fee',
'type' => 'raw',
'value' => '$data->id',
'filter' => false,
'footer' => '$model->getTotal($data)',
'footerHtmlOptions' => array('class'=>'grid-footer'),
),
Notice the value of the type attribute is set to raw.
You can even use a PHP function and pass it the $data variable, like so:
array(
'name'=>'id',
'header' => 'User Fee',
'type' => 'raw',
'value' => function ($data) { ... handle $data how you like ... }
'filter' => false,
'footer' => '$model->getTotal($data)',
'footerHtmlOptions' => array('class'=>'grid-footer'),
),
For more information check out special variables in Yii

extendedSummary Yiiboster not show the sum total of gridview

I have gridview using TbExtendedGridView yii booster, in footer gridview i want show the sum of field using extendedSummary, i have follow the tutorial in yiibooster web but i can't show the extendedSummary to show the sum of column. Pls help me what's wrong in my code below ?. in the footer just show the box with blank text.
//this isi my gridview code
$no_loan= $_GET[no_loan];
$sql2="SELECT * from tbangsuran where nomor_pinjaman = '$no_loan' and status_bayar=1 order by no ASC";
$sqlProvider = new CSqlDataProvider($sql2);
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
//'filter'=>$model,
'id'=>'tbangsuran-grid',
'type'=>'striped bordered',
'template' => "{items}\n{extendedSummary}",
'dataProvider' =>$sqlProvider,
'columns'=>array(
array(
'name'=>'Angsuran Ke',
'headerHtmlOptions'=>array('style'=>'text-align:center; width:90px;'),
'htmlOptions'=>array('style'=>'text-align:center'
),
'value'=> '$data[\'no\']',
),
array(
'name'=>'Tanggal Tagihan',
'headerHtmlOptions'=>array('style'=>'text-align:center;width:90px;'),
'htmlOptions'=>array('style'=>'text-align:center'),
'value'=> 'date("d-m-Y",strtotime($data[\'tanggal_bayar\']))',
),
//'nomor_pinjaman',
array(
'name'=>'Tunggakan Pokok',
'headerHtmlOptions'=>array('style'=>'text-align:center; width:120px;'),
'htmlOptions'=>array('style'=>'text-align:right'),
'value'=> 'number_format($data[\'pastdue_pokok\'],0,"",".")',
),
array(
'name'=>'Tunggakan Bunga',
'headerHtmlOptions'=>array('style'=>'text-align:center; width:120px;'),
'htmlOptions'=>array('style'=>'text-align:right'),
'value'=> 'number_format($data[\'pastdue_bunga\'],0,"",".")',
),
array(
'name'=>'Total Tunggakan',
'headerHtmlOptions'=>array('style'=>'text-align:center;width:120px;'),
'htmlOptions'=>array('style'=>'text-align:right'),
'value'=> 'number_format($data[\'pastdue_pokok\']+$data[\'pastdue_bunga\'],0,"",".")',
),
),
'extendedSummary' => array(
'title' => 'Total Tunggakan',
'columns' => array(
'pastdue_pokok' => array('label'=>'Total Tunggakan','class'=>'TbSumOperation')
)
),
'extendedSummaryOptions' => array(
'class' => 'well pull-right',
'style' => 'width:300px'
),
));
You must use the same column name in extendedSummary field.
In your case would be:
'extendedSummary' => array(
'title' => 'Total Tunggakan',
'columns' => array(
'Total Tunggakan' => array('label'=>'Total Tunggakan','class'=>'TbSumOperation')
)
),
I recommend you to use short column name to this tasks.
Hope this helps!

Customised query to display in CGridView in yii

Controller,
$model=Product::model()->display_products_statistics();
$this->render('admin',array(
'model'=>$model,
));
View,
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'product-grid',
'dataProvider' => $model->display_products_statistics(),
'filter'=> $model,
'columns'=> array(
'member_count',
'seller_count',
'visitor_count',
'lowest price',
'desc',
'price',
'createdate',
'updatedate',
'opid',
'pimg',
array(
'class'=>'CButtonColumn',
),
),
));
Model,
$sql="select member_count,seller_count,
visitor_count from fc_product fp
group by member_count,visitor_count,seller_count
order by member_count desc";
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$products_statistics=$command->queryAll();
$dataprovider=new CArrayDataProvider($products_statistics,
array('pagination'=>false));
return $dataprovider->getData();
But then I am getting this error
Fatal error: Call to a member function getData() on a non-object in D:\wamp\www\yii\framework\zii\widgets\CBaseListView.php on line 111
I am confused and don't know what's going wrong.
Your problem is that you are not using CDataProvider in the correct way. CGridView needs an instance of CDataProvider to display, but you have used CDataProvider->getData() instead. I'd also recommend using CSqlDataProvider, which is purpose made for custom sql queries. Try this in your model;
$count = Yii::app()->db->createCommand('SELECT COUNT(*) FROM fc_product')->queryScalar();
$sql="select member_count,seller_count,
visitor_count from fc_product fp
group by member_count,visitor_count,seller_count
order by member_count desc";
return new CSqlDataProvider($sql, array(
'totalItemCount' => $count,
'sort' => array(
'attributes' => array(
'member_count', 'visitor_count', 'seller_count',
),
),
'pagination' => false

How to sort the fields from relation table in Yii?

I am trying to implement sorting with Yii list view. I have joined 2 tables named provider_favourite and service_request in list view. And the fields and contents from both tables are listing in the list view. But sorting is working only in provider_favourite table, not from service_request table.How can I sort the fields from service_request table? Iam using csort for sorting. I also tried CGrid view. But the same problem is happening in grid view also ..
Iam using the following code to join
$criteria = new CDbCriteria;
$criteria->select = 'favourite_notes,favourite, favourite_added_date,max_budget,preferred_location,service_name';
$criteria->join = 'LEFT JOIN service_request AS s ON service_request_id = favourite';
$criteria->condition = 'favourite_type = 1';
$sort=new CSort('ProviderFavourite');
// $sort->defaultOrder='s.max_budget ';
$sort->applyOrder($criteria);
$sort->attributes = array(
'max_budget' => 'service_request.max_budget',
'service_name' => 'service_request.service_name',
'favourite_added_date'
);
$type = 2;
$data = new CActiveDataProvider('ProviderFavourite', array('criteria' => $criteria, 'pagination' => array('pageSize' => 4),'sort'=>$sort
));
$this->renderPartial('favourites', array(
'ModelInstance' => ProviderFavourite::model()->findAll($criteria),
'dataProvider' => $data, 'type' => $type, 'sort'=>$sort,
));
and also Iam providing sortable attributes in list view
$this->widget('zii.widgets.CListView', array('dataProvider'=>$dataProvider,'itemView'=>'index_1',
'id'=>'request',
'template' => ' {items}{pager}',
'sortableAttributes'=>array('favourite_notes','max_budget','service_name')
));
If more details needed, I will provide. Thanks in advance
You have to specify attributes property of your $sort instance. By default only fields of $modelClass (ProviderFavourite in your case) are sortable.
I think it could look like this (not tested):
$sort->attributes = array(
'service_name' => array(
'asc' => 's.service_name ASC',
'desc' => 's.service_name DESC'
),
// ...another sortable virtual attributes from service_request table
"*"
);
You should not create a CSort object in $sort. The CActiveDataProvider will already provide you with the right sort object. The way you do it, you apply the sort criteria to $criteria before you configure the sort attributes. That can not work.
You should try a simple setup like this instead:
$data = new CActiveDataProvider('ProviderFavourite', array(
'criteria' => $criteria,
'pagination' => array('pageSize' => 4),
'sort'=> array(
'attributes' => array(
'service_name' => array(
'asc' => 's.service_name ASC',
'desc' => 's.service_name DESC'
),
// ...
),
));
If you need to access the related CSort object (which you usually don't if you use a CGridView or CListView, because they deal with that for you), then you get it via $data->sort.

order data by desc order in default in YII

I am tyring to display somedata in desending order in YII view.HOw Do I order the data by studentID desc by default ?
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'student-grid',
'criteria'=>array(
'order'=>'StudentID DESC',
),
'dataProvider' => Agent::getStudents($model->agent_id),
'columns' => array(
'StudentID',
'first_name',
'last_name',
'dob',
'gender',
array(
'header' => 'Options',
'class' => 'CButtonColumn',
'template'=>'{View}',
'buttons'=>array(
'View' => array(
'url'=> 'Yii::app()->createUrl("/students/view/" . $data->StudentID)',
),
),
),
),
)); ?>
Thanks Ab
In your dataProvider (i assume that's what getStudents() function returns) add another array to your config array :) Like:
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$some_criteria,
/* Your array */
'sort'=>array(
'defaultOrder'=>array(
'StudentID'=>true,
),
),
/***/
));
Value 'false' in 'defaultOrder' array refers to ascending order, 'true' refers to descending order.
I hope that's what you're looking for :).
Also check out this forum thread: http://www.yiiframework.com/forum/index.php/topic/8428-cgridview-default-sort/
and this doc: http://www.yiiframework.com/doc/api/1.1/CSort#defaultOrder-detail
Regards.