How to hide a column in yii - yii

I want to hide a column in yii based on a condition. I have used a function in model. but visible functionality is not working in this column.
$this->widget('zii.widgets.grid.CGridview', array(
'id'=>'gridview',
'dataProvider'=>$dp,
'columns'=>array(
array(
'header' => 'Entries',
'value' => '$data->entry_name'
),
array(
'name' => 'value',
'value' => '$data->entry_name',
'visible'=>'$data->show()',
'type'=>'raw'
),
)
)
);
function in Model
public function show()
{
.........
return 1 or 0;
}
but it not working. Please help

I don't see a condition anywhere yet. You should use a comparison operator like return $this->attribute !== null; in your show function. Which returns true if attribute contains some value. Or if you want to do it on random you can return rand(0,1) == 1;.

Related

Yii, CGridView: filtering and sorting count column from related tables

I have 3 tables: productions, chunks (production may have a lot of chunks, so chunks contains production_id column) and chunk_designers (chunk may have a lot of designers, so chunk_designers has a column chunk_id).
I have to render data from productions in CGridView and add a column: count of chunks (for every production item in table), which are not assigned to any chunk. In other words:
SELECT COUNT(*) FROM `chunks`
left JOIN `chunk_designers`
ON chunks.id = chunk_designers.chunk_id
WHERE production_id = 520 AND chunk_id IS null
...where 520 - dynamic value for every row, productions.id.
ChunkController action:
function actionProductionList() {
$model = new Productions('search');
$model->unsetAttributes(); // clear any default values
$dataProvider = $model->search($_GET);
$dataProvider->criteria->order = 'start_time DESC';
$this->render('production_list', array(
'provider' => $dataProvider,
'model' => $model,
));
}
Model Productions:
class Productions extends AppModel {
....
public $unassignedBlocksCount;
....
public function rules() {
return array(
array('unassignedBlocksCount, id, ...', 'safe'),
array('unassignedBlocksCount, id, ...', 'safe', 'on'=>'search'),
);
}
//in search() I added:
$criteria->compare('unassignedBlocksCount', $this->unassignedBlocksCount, true);
}
And in view:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'menu-grid',
'dataProvider' => $provider,
'filter' => $model,
'enablePagination' => true,
'columns' => array(
array(
'name' => 'unassignedBlocksCount',
'value' => 'Chunks::getUnassignedBlocksCount($data->id)'
),
...
Column data is rendered fine, but when I try to filter it, I get the following error: unknown column unassignedBlocksCount in where clause.
I tried to write in search() method in Productions model:
// subquery to retrieve the count of posts
$count_sql = "(SELECT COUNT(*) FROM `chunks` "
. "LEFT JOIN `chunk_designers` "
. "ON chunks.id = chunk_designers.chunk_id "
. "WHERE production_id = 520 AND chunk_id IS NULL)";
// select
$criteria->select = array(
'*',
$count_sql . " as unassignedBlocksCount",
);
And just added unassignedBlocksCount element in columns in view.
But I still get the same error, when filter, and also problem is that I don't know, how to get production_id in $count_sql dynamically, depending on every table row (that's why in every row for that column value is 1, because it's correct value for production_id = 520).
So, my question is: how to get sortable and filterable column in CGridView, which is calculated (by COUNT()) from data in other tables? Thanks in advance.

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

Displaying value from join table in Yii CgridView

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',

Visibility of a button in cgridview based on the equality of two models fields

i have this array that represent the data for a button in a CGridView widget in YII.
array(
'Button' =>
array(
'imageUrl'=>Yii::app()->request->baseUrl.'/images/image.png',
'url'=>'Yii::app()->createUrl("controller/action", array("column"=>$data->column))',
'visibile'=>'$visibile',
))
I need $visibile to be true or false based on this function:
if (array_key_exists(0 , Table::model()->findAllByAttributes(array('column' => $model->column)))){
$visible = true;
}
else {
$visibile = null;
}
where Table::model is not the same model of the grid.
How can i modify the visibility of the button based on the equality of the value in the record of this model and the model of the view?
I hope my question was clear, thanks everyone!
You could do this in Yii
array(
'Button' =>
array(
'imageUrl'=>Yii::app()->request->baseUrl.'/images/image.png',
'url'=>'Yii::app()->createUrl("controller/action", array("column"=>$data->column))',
'visibile'=>function($index, $data) {
// the logic, where $data is the model for that row
// ...
// return true(visible) or false(invisible)
},
))
Following might work for you:
array(
'Button' =>
array(
'imageUrl'=>Yii::app()->request->baseUrl.'/images/image.png',
'url'=>'Yii::app()->createUrl("controller/action", array("column"=>$data->column))',
'visibile'=>"return array_key_exists(0 , Table::model()->findAllByAttributes(array('column' => $model->column)));",
))

how to handle an array as a field in CGridView

I'm using CGridView but one of the field is an array ['xx' ,'yy' , 'zz',...]
How can I display that i searched for an answer but did not find
is it possible to use something like DropDownlist to display the values in the array
I have a static array special_offer in a model;
It will filter by the value; This is a drop down list example;
I replaced a field within the cgridview with a array as follows:
array(
'name' => 'special_offer',
'value' => 'Package::$special_offer[$data->special_offer]',
'filter' => Package::$special_offer,
),
In order to use dropDownList in a CGridView column, your array needs to be associative. I recommend that you create a method in your model which converts it into an associative array, something like:
public function getAssociativeArray()
{
$array = array('xx', 'yy', 'zz'); // or use an attribute value
return array_combine(array_values($array), $array);
}
Then in your CGridView, add this as a column, replacing the model/field names with your own:
array(
'name' => 'yourFieldName',
'type' => 'raw',
'value' => 'CHtml::activeDropDownList($data, "yourFieldName", YourModel::model()->associativeArray)',
),