Submit CGridView Checked values using a form - php

I have a CGridView wigdet with CCheckBoxColumn like this:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
array(
'class'=>'CCheckBoxColumn',
),
'title',
....
),
));
Question: how to submit to controller action the checked values? I understand that I need a form, submit button, but I need a clear explanation where to put things, so that search boxes on the top appear.
Thanks in advance.

You do not absolutely need another form. You can just use a link with additional javascript attached to it.
To get the checked values, you can call the javascript function $.fn.yiiGridView.getChecked(containerID,columnID), see here, it returns an array containing the ids.
Full example (with ajax):
In your view:
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'example-grid-view-id', // the containerID for getChecked
'dataProvider'=>$dataProvider,
'columns'=>array(
array(
'class'=>'CCheckBoxColumn',
'id'=>'example-check-boxes' // the columnID for getChecked
),
'title',
....
),
));
?>
<div id="for-link">
<?php
echo CHtml::ajaxLink('SomeLink',Yii::app->createUrl('somecontroller/someaction'),
array(
'type'=>'POST',
'data'=>'js:{theIds : $.fn.yiiGridView.getChecked("example-grid-view-id","example-check-boxes").toString()}'
// pay special attention to how the data is passed here
)
);
?>
<div>
In your controller:
...
public function actionSomeaction(){
if(isset($_POST['theIds'])){
$arra=explode(',', $_POST['theIds']);
// now do something with the ids in $arra
...
}
...
}
...
You could also use json string, instead of simple string, in the data we pass by ajax (from the view), but then instead of explode(), you would use json_decode() (in the controller). Also it would be better to validate/sanitize the ids before use.
Check out the documentation for CHtml::ajaxLink to know more about ajax links.
Note that the example is a little crude, since i haven't put in checks for empty array of checked ids.

This one works with CSRF protection and updates the GridView.
<?php
echo CHtml::ajaxLink('ClickMe',Yii::app()->createUrl('controller/action'),
array(
'type'=>'POST',
'data'=>'js:{"ids" : $.fn.yiiGridView.getChecked("grid_view_id","check_box_id").toString(),"YII_CSRF_TOKEN" : "'.Yii::app()->request->csrfToken.'"}',
'success'=>"$('#grid_view_id').yiiGridView.update('grid_view_id')"
));
?>

If you wrap your Gridview into a simple form you can send the checkboxs selected to the value,
An example:
View
<form id="frmSubmit">
<?php
echo CHtml::dropDownList('user_id'
, null
, CHtml::listData(User::model()->findAll(), 'USER_ID', 'FULLNAME')
);
echo CHtml::ajaxSubmitButton('Save'
, Yii::app()->createUrl('query/ajaxUpdate')
, array('success' => 'js:reloadGrid', )
, array('class' => 'btn btn-success'));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'query-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'id' => 'query',
'class'=>'CCheckBoxColumn',
'selectableRows' => '2',
),
'Contact',
'Email',
'Company',
),
)); ?>
</form>
<script type="text/javascript">
function reloadGrid(data) {
$.fn.yiiGridView.update('query-grid');
}
</script>
Controller
public function actionAjaxUpdate()
{
var_dump($_POST);
}

Related

yii CButtonColumn in gride view gives error

i have a admin page with CGrideView , but when i want to change my button column to add some other buttons gives this error : CButtonColumn and its behaviors do not have a method or closure named "getId".
admin action :
public function actionAdmin()
{
$model=new Block('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['Block'])) {
$model->attributes=$_GET['Block'];
}
$this->render('admin',array(
'model'=>$model,
));
}
admin view :
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'block-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'name',
'content',
'type',
'enable',
array(
'class'=>'CButtonColumn',
'template' => '{view}{update}',
'buttons' => array(
'update' => array(
'url' => 'Yii::app()->controller->createUrl("update", array("name"=>$data->name))'
),
'view' => array(
'url'=>'CController::createUrl("view", array("name"=>$data->name))'
),
),
),
)));
solved! the reason is in the :
'view'=>array(
'url'=>'CController::createUrl("view",array("name"=>$data->name))'
),
it should be :
'view'=>array(
'url'=>'Yii::app()->controller->createUrl("view", array("name"=>$data->name))'
),
and why ?
because ():
Because Yii::app()->controller it is instance Controller of current application. Controller have property private $_id. CController::createUrl it is just static method. In method createUrl() calls method $this->getId(), but when you call static method instance is not created-#DanilaGanchar .
so in CController::createUrl it can't find the id of controller and for use that i should give it argument like this CController::createUrl("/page/view",array("name"=>$data->name)) i try that now and worked
The order of elements in template must be equal to the order of element in buttons. You have {view}{update} as the template, but you have defined update button first! So I think changing 'template'=>'{view}{update}' into 'template'=>'{update}{view}' probably can solve your problem.

Yii - CGridView rows / column values as link and calling ajax function on click

In a YII based project I have a cgridview. Requirement is to make whole row or every column value a link and clicking on any of link in row will fire an ajax call. I have tried it from here
How to display rows of CGridView as a link
but issue it that If i make whole row as clickable it takes me to view action.
If I make individual column values in a row as a link and call ajax function i get following error.
Property "CDataColumn.options" is not defined.
I need help in making whole row as clickable and call an ajax function or individual row values to call an ajax function on click.
Any help or guidance in right direction is greatly appreciated.
//code for making trading name column in cgridview as clickable and call ajax
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'customer-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
array(
'name' => 'trading_name',
'value' => 'CHtml::link($data->trading_name, Yii::app()
->createUrl("customer/view/",array("id"=>$data->primaryKey)))',
'type' => 'raw',
'options' => array('ajax' => array('type' => 'get', 'url'=>'js:$(this).attr("href")',
'success' => 'js:function(data) {
$("#tab1").html(data);')
),
),
'email',
'site_code',
array(
'class'=>'CButtonColumn',
),
After some hassle I was able to make the row of the cgridview a link and on clicking on the each row calls an AJAX function. Below is the code. May be it is helpful for someone.
selectionChanged did the trick. On clicking any row calls an ajax function and displays
each customer's information a div below grid.
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'customer-grid',
'dataProvider'=>$model->search(),
'selectionChanged'=>'js:function(id){
n = $.fn.yiiGridView.getSelection(id);
if (n>0){
$.ajax({
url: "'.Yii::app()->urlManager->createUrl('customer/view/').'",
type: "GET",
data: {"id": parseInt(n)},
dataType: "html",
success: function(data) {
$("#customer-div").html(data);
}
});',
'filter'=>$model,
'columns'=>array(
'id',
array(
'name' => 'trading_name',
'value' => 'CHtml::link($data->trading_name, Yii::app()
->createUrl("customer/view/",array("id"=>$data->primaryKey)))',
'type' => 'raw',
'options' => array('ajax' => array('type' => 'get', 'url'=>'js:$(this).attr("href")',
'success' => 'js:function(data) {
$("#tab1").html(data);')
),
),
'email',
'site_code',
array(
'class'=>'CButtonColumn',
),
'options' is not possible for a cgridview column as said in yii documentation :
http://www.yiiframework.com/doc/api/1.1/CGridColumn#htmlOptions-detail
You have to use 'htmlOptions' if you wan to set options.
But if you want to use ajax with a link, you have to use Chtml::ajaxLink() :
http://www.yiiframework.com/doc/api/1.1/CHtml#ajaxLink-detail
I hope it helps you

Yii CGridView update

So I gave up on all of the above and decided to move the colums I wanted to show with ajax in a different grid in the main grid but for some reason i get this error:
Trying to get property of non-object
/var/www/html/framework/base/CComponent.php(607) : eval()'d code(1)
<?php
$this->breadcrumbs=array(
'Fund Admin'=>array('/FundAdmin/index/'),
'Contract Notes'=>array('index'),
'List',
);
$user = Yii::app()->user;
$this->menu=array(
array('label'=>'Fund Prices', 'url'=>array('/FundPrice/index'), 'visible'=>$user->checkAccess('listFPrice')),
array('label'=>'Reports','url'=>array('/FundAdmin/index'), 'visible'=>$user->checkAccess('listReports')),
array('label'=>'Create Contract Note', 'url'=>array('create'), 'visible'=>$user->checkAccess('createCNote')),
array('label'=>'Audit Contract Note', 'url'=>array('auditList'), 'visible'=>$user->checkAccess('auditListClient')),
//array('label'=>'Audit Contract Note Item', 'url'=>array('/ContractNoteItem/auditList'), 'visible'=>$user->checkAccess('auditListClient')),
);
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$.fn.yiiGridView.update('contract-note-grid',{
data: $(this).serialize()
});
return false;
});
");
?>
<h1>List Contract Note</h1>
<p>
You may optionally enter a comparison operator (<b><</b>, <b><=</b>, <b>></b>, <b>>=</b>, <b><></b>
or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.
</p>
<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php
//$data=NULL;
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'contract-note-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'name'=>'cn_fund_house_id',
'type'=>'raw',
'value'=>'$data->cnFundHouse->fh_name',
),
array(
'name'=>'contractNoteItems.cni_fund_id',
'type'=>'raw',
'value'=>'$data->contractNoteItems->f_name',
),
array(
'name'=>'contractNoteItems.cni_isin',
'type'=>'raw',
'value'=>'$data->contractNoteItems->cni_isin',
),
array(
'name'=>'contractNoteItems.cni_client_account_no',
'type'=>'raw',
'value'=>'$data->contractNoteItems->cni_client_account_no',
),
'cn_investment_date',
//'cn_settlement_date',
array(
'class'=>'CButtonColumn',
'deleteConfirmation'=>'Are you sure you want to retire this item?
This item needs to be audited for retirement to take effect.',
'template'=>'{view}{update}{delete}',
'buttons'=>array(
'view' => array
(
'label'=>'view',
'url'=>'Yii::app()->controller->createUrl("contractNoteItem/view",array("id"=>$data->getCNIid($data->id)))',
'visible'=>"Yii::app()->user->checkAccess('editFund')",
),
'update' => array
(
'label'=>'edit',
'url'=>'Yii::app()->controller->createUrl("edit",array("id"=>$data["id"]))',
'visible'=>"Yii::app()->user->checkAccess('editFund')",
),
'delete' => array
(
'label'=>'retire',
'url'=>'Yii::app()->controller->createUrl("retire",array("id"=>$data["id"]))',
'visible'=>'$data->checkIfRetired($data["id"])',
)
)
),
),
));
?>
And the particular error comes to the )); right before the php closing tag so I do not understand. If I comment the 'value' for each of the arrays except the first one and the CButtonColumn arrays I don't get the error because I just don't populate the fields with data. So I don't really get why it does this because everything in the models are defined right.
Also note that when I upload the file to my live server I do not get the error but the colums does not show for these colums:
array(
'name'=>'contractNoteItems.cni_fund_id',
'type'=>'raw',
'value'=>'$data->contractNoteItems->f_name',
),
array(
'name'=>'contractNoteItems.cni_isin',
'type'=>'raw',
'value'=>'$data->contractNoteItems->cni_isin',
),
array(
'name'=>'contractNoteItems.cni_client_account_no',
'type'=>'raw',
'value'=>'$data->contractNoteItems->cni_client_account_no',
),
The live server php is 5.3.27 and on my local server is 5.3.3 so I do not know why I get the error on the local. Anyway my question is about the data there not showing and giving me the error on the local server.
I think you issues is in your button area you have lines like this:
'visible'=>'$data->checkIfRetired($data["id"])',
However $data should be an object not an array. Try changing it to:
'visible'=>'$data->checkIfRetired($data->id)',
In reality though you should need to pass any data to functions like checkIfRetired since it is already an instance. In the function you should just be able to use the value $this->id instead of having to pass it.
The value elements for your columns are the problem. When the value element of a column is not specified, Yii checks whether the object exists before getting the value of the desired attribute. Your value elements do not have this check hence the error.
For simplicity in your code, there is no need to add the value and type elements for some columns. As such your code becomes
'columns'=>array(
...
'contractNoteItems.cni_fund_id',
'contractNoteItems.cni_isin',
'contractNoteItems.cni_client_account_no',
...
)
For more information, see CGridView.columns

To change the value of parameter in CGridView using Yii

I a have a basic question about CGridViews. I have the table employees stored in my DB and I am showing some of his atributs using this CGridView. The problem is that I stored all the passwords using the md5 codification, and when I want to show them I don't know how to show them without the md5 codification.
I tried it with the sentence: "'password'=>$dataProvider->employee->md5(password)," But as you can imagine it is wrong and it doesn't work. This is my CGridView with parameter password changed to this sentence.
<?php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'id'=>'employee_list',
'columns'=>array(
'id',
'name',
//'password',
'password'=>$dataProvider->employee->md5(password),
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Somebody could help me? Thank you very much.
you just need to pass php code as string, Cgridview will run that string with eval function,
Please refer following code for more clarification:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->search(),
'columns'=>array(
array(
'name'=>'password',
'value'=>'md5($data->password)',
),
),
));
Let say you encoded your password with base64_encode($password) then what you have to do is base64_decode($encoded_password)
from your question, is it $dataProvider->md5(password)?
maybe you can refer the code below.
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'leaveapplication-grid1',
'dataProvider'=>$model->searchpersonalleave($myid),
//'filter'=>$model,
'columns'=>array(
'leave_dateapplied',
'leave_id',
array('name'=>'leave_category','value'=>'$data->getcategoryname($data->leave_category)' ), //0-annual, 1-medical, 2-emergency
'leave_startdate',
//'leave_enddate',
'leave_duration',
'leave_reason',
array(
'class'=>'CButtonColumn',
'template'=>'{view}{update}',
'buttons'=>array
(
'update' => array
(
'visible'=>'($data->getupdatefunction(17) =="Yes")',
),
),
),
),
));

Data isn't displaying from another table in CGridView Widget

I have two table Event and EventCategory. I am using zii.widgets.grid.CGridView widget to display all the events in the admin section.
I have created the following relations between tables.
Relation in EventCategory model:
'event' => array(self::HAS_MANY, 'Event', 'category_id'),
Relation in Event model:
'category' => array(self::BELONGS_TO, 'EventCategory', 'category_id'),
The following code I am using to display the Events:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'event-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'summaryText'=> '',
'columns'=>array(
array('header'=>'Id','name'=>'event_id','filter'=>''),
'event_code',
'category.evntcatm_name',
'event_name',
array(
'class'=>'CButtonColumn',
'htmlOptions'=>array('class'=>'actions aligncenter'),
'deleteButtonImageUrl'=>false,
'updateButtonImageUrl'=>false,
'viewButtonImageUrl'=>false
),
),
)); ?>
'category.evntcatm_name' doesn't display anything. It is just creating the blank column with NO ERROR. What I am missing here.
Please try something like it
$data->category->evntcatm_name
You should use code like this:
'columns' = array(
/*YOUR DATA*/
array(
'name' => 'category_id',
'value' => function($data) {
return !empty($data->category) ? $data->category->evntcatm_name : null;
}),
)
This way can solve your problem with "Trying to get property of non-object". If you see blank cell in grid that means you miss relation (or it doesnt exist, in this way you should check relation condition or database)
Here is a few wild guesses:
Is category.evntcatm_name correctly spelled?
Is there actually data in the evntcatm_name field to begin with?
I know it might sound too simple to miss, but the error almost has to be on that level.
Try finding a category using the primary key and output it's evntcatm_name.
$cat = EventCategory::model()->findByPk(1);
echo $cat->evntcatm_name;
Maybe if you could share your schema for those two tables?
You can use
array(
'header' => 'Category Title',
'value' => '$data->category->evntcatm_name'
),
instead of 'category.evntcatm_name'
The model instance is not object now in the Cgidview:
Try
$data['category']['evntcatm_name'];

Categories