remove button from CGridView with condition - yii

Hi I have CRUD generated CGridView in yii. I need to add a new button to CGridView rows and hide it if appointment_status(one of CGridView column) value equals 0
This is my code of CGridView,
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'bookings-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'id',
'name',
'email',
'telephone',
'time',
'employee',
'appointment_status',
'client_ip',
'link' => array(
'header' => 'Confirmation',
'type' => 'raw',
'value' => 'CHtml::button("$data->appointment_status",array("onclick"=>"document.location.href=\'".Yii::app()->controller->createUrl("controller/action",array("id"=>$data->id))."\'"))',
'visible'=>$data->appointment_status==1,
),
array(
'class' => 'CButtonColumn',
),
),
));
But all I'm getting is error stating,
Undefined variable: data
It would be great help if someone can look into it.

you can use like this:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'bookings-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'id',
'name',
'email',
'telephone',
'time',
'employee',
'appointment_status',
'client_ip',
'link' => array(
'header' => 'Confirmation',
'type' => 'raw',
'value' => function ($data) {
if ($data->appointment_status == 1) {
return CHtml::button("$data->appointment_status", array("onclick" => "document.location.href=\'" . Yii::app()->controller->createUrl("controller/action", array("id" => $data->id)) . "\'"));
} else {
return;
}
}
),
array(
'class' => 'CButtonColumn',
),
),
));

Your 'visible' handling the column visibility and not the button, you can use custom attribute on model to create and handle the button visibility.
add to your model:
public function getConfirmationButton()
{
if ($data->appointment_status == 1) {
return CHtml::button($this->appointment_status,array("onclick"=>"document.location.href=\'".Yii::app()->controller->createUrl("controller/action",array("id"=>$this->id))."\'"));
} else {
return '';
}
}
and call it in your view:
..........
'link' => array(
'header' => 'Confirmation',
'type' => 'raw',
'value' => '$data->confirmationButton',
),
...........

visible is a boolean or a PHP expression that will be evaluated to give a boolean. During the evaluation $data is assigned to the current item from the dataProvider used. $data doesn't exist outside of the evaluation function evaluateExpression(). As such the implementation should be:
`visible` => '$data->appointment_status == 1',

You need to quote value of visible key in link array. So instead of this:
'visible'=>$data->appointment_status==1
It should be:
'visible'=>'$data->appointment_status==1'
it should work now.

You will get undefined variable because visible not allow any callback.
Try this solution, it's yii2 code and i don't know much of Yii.
'delete' => function ($url, $model) {
return ($model->isVisible($model)) ?
Html::a('<span class="glyphicon glyphicon-trash"></span>',
$url,
['title' => Yii::t('app', 'Delete')]) : '';
public static function isVisible($data)
{
return ($data->appointment_status == 1) ? true : false;
}

Related

CGridView show columns

I have a status field, which should be highlighted in green or red, depending on where 0 or 1. I have the following code, but it does not work, all the cells in a single color paint. Tell me how to do such a thing?
array(
'name' => 'status',
'htmlOptions' => array('class' => $model->status == 0 ? "non_payed_status" : "payed_status"),
'filter' => false,
),
You have to override CDataColumn class, look at this, maybe will help:
http://www.yiiframework.com/wiki/314/cgridview-use-special-variable-data-in-the-htmloptions-of-a-column-i-e-evaluate-htmloptions-attribute/
You can do this with callback function.
in view - CGridView column
array(
'name' => 'status',
'value' => array($this,'status_color'), // status_color is callback method
'htmlOptions' => array('class' => $model->status == 0 ? "non_payed_status" : "payed_status"),
'filter' => false,
),
In controller class
public function status_color($data)
{
if($data->status)
{
echo '<div class="payed_status">Active</div>';
}else{
echo '<div class="non_payed_status">Inactive</div>';
}
return false;
}
try this, hope it will help you.
array(
'name' => 'status',
'htmlOptions' => array('class' => $data->status == 0 ? "non_payed_status" : "payed_status"),
'filter' => false,
),
Just change $model->status to $data->status. Let me know if its working.
Try to add
'type'=>'raw'
array(
'name' => 'status',
'htmlOptions' => array('class' => $model->status == 0 ? "non_payed_status" :"payed_status"),
'filter' => false,
'type'=>'raw'
),

Nested Whgridview. Grids disappear on sort or pagination click

I'm a newbie in Yii programming.
I'm using boostrap library on Yii via Yiistrap/Yiiwheels
I've created a relation table view
The related view is a Whgridview itself
The first (master grid) has a TbRelationColum clicking it i display the second grid (detail grid).
When I click on the row to display the sub grid, everything appears ok. When I change the sort order or the page of the sub grid disappear both grid.
I understand we should differentiate the css class of the pager and the sort of sub grid from the main grid. How to do this specifically in Yii-Way?
Is This the problem?
This is the view of the main grid:
$this->widget('yiiwheels.widgets.grid.WhGridView',array(
'id'=>'masterGrid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'template' => "{summary}{items}<div class=\"row-fluid\"><div class=\"pull-right\">{pager}</div></div>",
'type' => array(TbHtml::GRID_TYPE_BORDERED, TbHtml::GRID_TYPE_STRIPED),
'columns'=>array(
array(
'class' => 'yiiwheels.widgets.grid.WhRelationalColumn',
//'name' => 'multiMembers.id',
'type' => 'raw',
'header' => 'Sub Items',
'url' => $this->createUrl('multiGroup/ajaxSubItems'),
'cacheData' => false,
'value' => "CHtml::tag('button',array('class'=>'btn btn-primary'),'Sub Items')",
'htmlOptions'=>array('style'=>'width:90px;'),
'cssClass' => 'showSubItems',
),
'id',
'title',
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
),
),
));
This is the sub-grid:
echo CHtml::tag('h3',array(),'Sub Items Group #"'.$id.'"');
$this->widget('yiiwheels.widgets.grid.WhGridView', array(
'id'=>'subGrid_'.$id,
'type'=>array(TbHtml::GRID_TYPE_BORDERED, TbHtml::GRID_TYPE_STRIPED),
'dataProvider' => $gridDataProvider,
'template' => "{summary}{items}<div class=\"row-fluid\"><div class=\"pull-right\">{pager}</div></div>",
'columns' => $gridColumns,
));
This is the controller:
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new MultiGroup('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['MultiGroup'])) {
$model->attributes=$_GET['MultiGroup'];
}
$this->render('admin',array(
'model'=>$model,
));
}
public function actionAjaxSubItems()
{
$id = Yii::app()->getRequest()->getParam('id');
$model = $this->loadModel($id);
if($model->numSubItems > 0) {
$this->renderPartial('_child', array('id' => $id,
'gridDataProvider' => $this->getGridDataProvider($id),
'gridColumns' => $this->getGridColumns()
), false, true);
} else {
echo 'Non ci sono Sub Items.';
}
}
public function getGridDataProvider($id) {
$sql = 'SELECT * FROM multi_member WHERE groupid = :groupid ORDER BY lastname,firstname';
$cmd = Yii::app()->db->createCommand($sql);
$cmd->bindParam(':groupid', $id, PDO::PARAM_INT);
$result = $cmd->queryAll();
$dataProvider = new CArrayDataProvider(
$result, array(
'sort' => array(
'attributes' => array('id','groupid','firstname','lastname','membersince'),
'defaultOrder' => array('lastname' => CSort::SORT_ASC, 'firstname' => CSort::SORT_ASC),
),
'pagination' => array(
'pageSize' => 2,
),
));
return $dataProvider;
}
public function getGridColumns() {
return array('id', 'lastname', 'firstname', 'membersince');
}
How can I do?
thank you ..
If the extensions you're using all extend CGgridView, then you should be able to use option 'ajaxUpdate' (link to documentation).
Try setting 'ajaxUpdate'=>false in one of the grids (or in both of them) to see whether it helps you.
Sometimes setting ajaxUpdate to false is the only way I get get some grids to behave the way I want them to...

Change imageUrl with user_status field in user table

I have to model: User, UserFlag
In User/index added a column in CGridView:
array(
'class' => 'CButtonColumn',
'htmlOptions' => array("style" => 'width: 45px;'),
'template' => '{enable}',
'header' => 'management',
'buttons' => array(
'enable' => array(
'name' => 'enable',
'imageUrl' => Yii::app()->baseUrl."/images/ico/group.png",
'url' => '"#".$data->username',
'click' => 'js:function() {
if(confirm("Are you sure?")){
changeUserStatus($(this).attr("href").replace("#", ""));
}
}',
),
),
I will read user status from UserFlag Model and if status is active I show 1.png and if status is deactive I show 2.png.
Yeah, the $data var isn't accessible from imageUrl unfortunately. I would recommend extending from CButtonColumn like Stu's link suggested.
If you don't want to do that you could create two button columns and show them depending on the status. It would be something like this but you may need to adjust it if your active user_status value isn't 1 or you want the images reversed:
'enable' => array(
'name' => 'enable',
'visible'=>'$data->user_status == 1'
'imageUrl' => Yii::app()->baseUrl."/images/ico/1.png",
'url' => '"#".$data->username',
'click' => 'js:function() {
if(confirm("Are you sure?")){
changeUserStatus($(this).attr("href").replace("#", ""));
}
}',
),
'disable' => array(
'name' => 'disable',
'visible'=>'$data->user_status == 0'
'imageUrl' => Yii::app()->baseUrl."/images/ico/0.png",
'url' => '"#".$data->username',
'click' => 'js:function() {
if(confirm("Are you sure?")){
changeUserStatus($(this).attr("href").replace("#", ""));
}
}',
),
You would also need to add {disable} to your CButtonColumn template.
It's not ideal since you're repeating code, but at least you can do it without having to extend any classes.

Invalid type given. String expected - Zend Framework 2

Im working on Zend Framework 2 especially with Zend Forms. I have declared a Select dropdown box in
Form:
$selectElement = new Element\Select('selectElement');
$selectElement->setAttribute('title', 'Select a Value')
->setAttribute('id', 'id');
$data = array(
array(
//Fetching the values from database
),
);
$selectElement->setAttribute('multiple', 'multiple')
->setValueOptions($data);
$this->add($selectElement);
InputFilter:
$inputFilter->add($factory->createInput(array(
'name' => 'selectElement',
'required' => false,
'filters' => array(
array(
'name' => 'Int'
),
),
)));
I have used Zend Debug to get the values which are in the selectElement dropbox in this fashion:
$dataSelectElements = $this->getRequest()->getPost('selectElement');
\Zend\Debug\Debug::dump($dataSelectElements);
Debug Result:
array(4) {
[0] => string(2) "20"
[1] => string(2) "22"
[2] => string(2) "23"
[3] => string(2) "75"
}
Basically Im getting the id's from the selectElement form to store it in the database. Right now Im getting a notice and zend form error:
Notice Error:
Notice: Array to string conversion in ..\zendframework\zendframework\library\Zend\Filter\Int.php on line 29
And a form invalid error:
array(1) {
[0] => array(1) {
["selectElement "] => array(1) {
["explodeInvalid"] => string(35) "Invalid type given. String expected"
}
}
}
Is there a solution to over come this problem. Any help would be appreciated.
The Int filter will attempt to make an Integer out of your array of data, which is not going to work.
Previously I've used the Callback filter, which can be used to loop through the data and check if each value is an Int.
For example:
'filters' => array(
array(
'name' => 'Callback',
'options' => array(
'callback' => function($values) {
return array_filter($values, function($value) {
return ((int)$value == $value);
});
}
)
),
),
I did bit differently, something like this
form
class Companyform extends Form
{
public function __construct()
{
// we want to ignore the name passed
parent::__construct('company');
$this->setAttribute ('method', 'post');
$this->setAttribute ('class', 'form-horizontal');
$this->add ( array (
'name' => 'parentID',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'id' => 'parentID',
'type' => 'select',
'placeholder' => "Parent Company",
),
'options' => array(
'label' => 'Parent Company'
)
));
$this->add(array(
'name' => 'btnsubmit',
'attributes' => array(
'id' => 'btnsubmit',
'type' => 'submit',
'value' => 'Add',
'class' => 'btn btn-primary'
),
));
}
}
controller
public function addAction()
{
$request = $this->getRequest();
$companyList = $this->_getCompanyList();
$form = new Companyform();
$form->get('parentID')->setAttribute('options',$companyList);
if ($request->isPost())
{
$company = new Company();
$form->setInputFilter($company->getInputFilter());
$form->setData($request->getPost());
if ($form->isvalid())
{
}
}
}
public function _getCompanyList()
{
$companies = $this->Em()->getEntityManager()->getRepository('XXXX\Entity\Company')->findBy(array('isDeleted'=>'0'));
$companyIDList = array();
$companyIDList[0] = "No Parent";
foreach ($companies as $company)
{
$companyIDList[$company->id] = $company->companyName;
}
return $companyIDList;
}
Entity class
protected $inputFilter;
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'companyName',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 255,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
You may need to add following library in entity
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
In ZendFramework 2, when you creating a (add) element from your Form file, Check the attribute: inarrayvalidator is true.
$this->add(array(
'name' => 'select_name',
'type' => 'select',
'id' => 'select_name',
'options' => array(
'label' => 'Select Name',
),
'attributes' => array(
'id' => 'select_id',
'inarrayvalidator' => true,
),
));
I hope, this works...

Populating CGridView one to many relation

In my project one of the model named types having multiple relation to other models the criteria with part is giving below its like
$criteria->with = array(
'category',
'subCategory',
'accountsSupplierPriceDetails' => array(
'with' => 'serviceLevel'
)
);
the relationship goes like
types - category - relation(1-1)
types - subcategory - relation(1-1)
types - accountsSupplierPriceDetails - relation(1-1)
accountsSupplierPriceDetails - serviceLevel - relation(1-n)
my problem is how to display the names from each table in a grid. the result of (1-n) should be displayed in a dropdownbox. when i try to access the data from column it shows the error Trying to get property of non-object ($data->accountsSupplierPriceDetails->serviceLevel ->name). can anyone please help me.
Thanks in advance.
in my view i create a cgridview with 5 rows in which one row data is populated using dropdownlist.
<div style="width:700px; height:auto;">
<?php
$widget = $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'response-grid',
'dataProvider' => $pickdataset->pickCategorylistingForMain(),
'cssFile' => Yii::app()->baseUrl . '/media/css/gridview.css',
'summaryText' => '',
'ajaxUpdate' => 'response-grid',
'enablePagination' => true,
'pager' => array(
'class' => 'LinkPager',
'cssFile' => false,
'header' => false,
'firstPageLabel' => 'First',
'prevPageLabel' => 'Previous',
'nextPageLabel' => 'Next',
'lastPageLabel' => 'Last',
),
'columns' => array(
array(
'name' => 'id',
'header' => '#',
'value' => '$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
),
array(
'type' => 'raw',
'name' => 'categoryExt',
'header' => 'Category',
),
array(
'type' => 'raw',
'header' => 'Sub Category',
'value' => '$data->subCategory->name',
),
array(
'type' => 'raw',
'name' => 'locationExt',
'header' => 'Location',
),
array(
'type' => 'raw',
'header' => 'Name',
'value' => 'CHtml::dropDownList($data->corporate_id."-".$data->category_id."-".$data->sub_category_id."-".$data->location_id,"",popDropBox($data->masterCategoryServiceLevels), array("class" => "listbox"), array("empty" => "Select a Location"))',
),
array(
'type' => 'raw',
'header' => 'Pick',
'value' => 'CHtml::image(Yii::app()->baseUrl . "/media/images/edit_icon.png",$data->corporate_id."-".$data->category_id."-".$data->sub_category_id."-".$data->location_id,array("title" => "Select this Combination"))',
),
),));
function popDropBox($data)
{
$list = array();
foreach ($data as $row)
{
$list[$row->serviceLevel->id] = $row->serviceLevel->name;
}
return $list;
}
?>
</div>
the relation in model is:
'masterCategoryServiceLevels' => array(self::HAS_MANY, 'MasterCategoryServiceLevel', 'category_template_id'),
'corporate' => array(self::BELONGS_TO, 'AccountsCorporate', 'corporate_id'),
'category' => array(self::BELONGS_TO, 'MasterCategory', 'category_id'),
'subCategory' => array(self::BELONGS_TO, 'MasterCategory', 'sub_category_id'),
'location' => array(self::BELONGS_TO, 'MasterLocation', 'location_id'),
the row is
array(
'type' => 'raw',
'header' => 'Name',
'value' => 'CHtml::dropDownList($data->corporate_id."-".$data->category_id."-".$data->sub_category_id."-".$data->location_id,"",popDropBox($data->masterCategoryServiceLevels), array("class" => "listbox"), array("empty" => "Select a Location"))',
),
and i use a function to create dropdown data is
function popDropBox($data)
{
$list = array();
foreach ($data as $row)
{
$list[$row->serviceLevel->id] = $row->serviceLevel->name;
}
return $list;
}
please comment if you have any doubt. i am free to share... have a nice day SO friends... wishes and prayers.