To change the value of parameter in CGridView using Yii - php

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")',
),
),
),
),
));

Related

How to get the checkbox to appear in entire column PHP Yii1.1

I am trying to make the checkbox appear in the entire column of my view. However, I am a little lost as to the 'value' of said column. As of right now, I have no clue what I need to enter to make the checkbox appear in the entire column at all.
Any help or advice is appreciated. Below is the code I have written so far.
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'ServiceDataProvider',
'dataProvider'=>$model->search(),
'cssFile' => false,
'filter'=>$model,
'columns'=>array(
array(
'header'=>'Affected Groups',
'value'=>'displayGroupName($data->groups)',
'name'=>'groups.description',
'filter'=>CHtml::textField('groups.description', Yii::app()->request->getParam('groups.description'))
),
array(
'header'=>'Affected Hosts',
'value'=>'displayHostName($data->hosts)',
'name'=>'hosts.hostname',
'filter'=>CHtml::textField('hosts.hostname', Yii::app()->request->getParam('hosts.hostname'))
),
array(
'name'=>'servicedescription',
),
array(
'class'=>'CButtonColumn',
'template'=>'{delete}',
'deleteButtonUrl'=>'Yii::app()->createUrl("path/to/delete",
array("id"=>$data["idservice"]))',
),
array(
'value'=>'', // AND this is the part where I have no clue what to do.
'id'=>'selectServices',
'header'=>'<input id="services_all" type="checkbox" title="Select multiple services to dele" data-toggle="tooltip"/>',
'headerHtmlOptions'=>array(
'class'=>'checkbox-column'
),
),
),
));
Thanks for your help, fellas. I really appreciate it.
Never mind. It's probably still early or something.
This is how I solved it with version Yii 1.1.21:
array(
'value'=>'$data->idservice',
'class'=>'CCheckBoxColumn',
'id'=>'selectServices',
'headerTemplate'=>'{item}',
'selectableRows'=>'2',
),

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'];

cgridview related fields filtering

I have a problem that I have solved for all but one of the cgridview filters, which is a related field.
I am using a solution Seenivasan has supplied but the related field status does not get added to the string.
here is the cgridview :-
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'tbl-orders-grid',
'dataProvider'=>$dataProvider,
'afterAjaxUpdate'=>"function() {
jQuery('#Orders_date_first').datepicker(jQuery.extend({showMonthAfterYear:false}, jQuery.datepicker.regional['id'], {'showAnim':'fold','dateFormat':'yy-mm-dd','changeMonth':'true','changeYear':'true','constrainInput':'false'}));
jQuery('#Orders_date_last').datepicker(jQuery.extend({showMonthAfterYear:false}, jQuery.datepicker.regional['id'], {'showAnim':'fold','dateFormat':'yy-mm-dd','changeMonth':'true','changeYear':'true','constrainInput':'false'}));
}",
'filter'=>$model,
'columns'=>array(
array(
'name'=>'id',
'type'=>'raw',
'value'=>'str_pad($data->id,8-strlen($data->id),"0",STR_PAD_LEFT)',
'htmlOptions'=>array('style' => 'text-align: right;width: 60px;')
),
array(
'name'=>'date_order_placed',
'filter'=>$dateisOn,
'value'=>'date("d-m-Y",strtotime($data->date_order_placed))',
),
array(
'name'=>'status',
'type'=>'raw',
//'htmlOptions'=>array('id' => 'order_status_search'),
'value'=>'CHtml::value($data,"status.orders_status_name")',
'filter'=>CHtml::listData(OrderStatus::model()->findAll(
array(
'select'=>array('orders_status_name'),
'distinct'=>true
)),"orders_status_name","orders_status_name")//this is the focus of your code
),
array(
'class'=>'EButtonColumnWithClearFilters',
'clearVisible'=>true,
'template'=>'{view}{email}',
'buttons'=>array
(
'email' => array
(
'label'=>'Reprint invoice and email to yourself',
'imageUrl'=>Yii::app()->request->baseUrl.'/images/email.png',
'url'=>'Yii::app()->createUrl("orders/ureprint", array("id"=>$data->id))',
),
),
),
),
)); ?>
here is the php and js that adds the current filter values to the url.
echo CHtml::button('List Orders',array('id'=>'listelement'));
Yii::app()->clientScript->registerSCript('test','
$("body").on("click","#listelement",function(){
var str="&";
$.each($("#tbl-orders-grid input").serializeArray(),function(i,j){
str=str+j.name+"="+j.value+"&";
});
window.location="'.CHtml::normalizeUrl(array('orders/index')).'"+str;
});
');
The other filters, dates and id, work perfectly. They are added to the url above. Status is not.
1- you need to define new filters in your model serach() methode for example like
$criteria->compare('Restaurant.Name',$this->Name,true);
Restaurant is your relation key , name : value from another table related to this fk
2- you have to add value of gridview column like :
view:
array(
'name' => 'Restaurant.Name',
'header' => 'Username',
'filter' => CHtml::activeTextField($model, 'name'),
'value' => '$data->Restaurant->Name',
This link will help you
yii CGridView filter with relations

Adding an ID attribute in the CButtonColumn not working

<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'material-logs-grid',
'dataProvider'=>$materialLogSearch->search(),
'filter'=>$materialLogSearch,
'ajaxUpdate'=> true,
'columns'=>array(
'po_number',
'qty_ordered',
array(
'name'=>'price',
'value'=>'number_format($data->price,2)',
'type'=>'raw'
),
array(
'name'=>'price',
'header'=>'Amount',
'value'=>'number_format($data->price*$data->qty_ordered,2)',
'type'=>'raw'
),
'date_ordered',
'note',
array(
'class'=>'CButtonColumn',
'template'=>'{update}{delete}',
'buttons'=>array(
'update'=>array(
'options'=>array(
'id'=>"myID-$data->idMaterial_logs",
),
),
),
'updateButtonUrl'=>"Yii::app()->createUrl(\"materialLogs/update\",array(\"id\"=>\$data->idMaterial_logs,\"pid\"=>\"$project_details->idProject\",\"mid\"=>\$data->idMaterials))",
'deleteButtonUrl'=>'Yii::app()->createUrl("/materialLogs/delete",array("id"=>$data->idMaterial_logs))',
),
),
));
?>
I'm getting this error
Undefined variable: data
The error occurs on this line:
'id'=>"myID-$data->idMaterial_logs",
What's the proper way to add an ID attribute on the CButtonColumn? I just wanted the Update Button to have a custom ID with it's corresponding id that is from my database($data->idMaterials);
So for example:
the id should be "myID-1", the 1 there is the value of idMaterial_logs, that is why I use $data->idMaterial_logs, which in this case it did not work.
Your help will be greatly appreciated and rewarded! Thanks! :)
Try to remove myID
'id'=>"myID-$data->idMaterial_logs",
To be
'id'=>'$data->idMaterial_logs',
The problem is taht you're using double quotes (") instead of single quotes (')
Because of this, the file will look for $data inside the view. It doesn't exist there.
Try this
<?php
'id' => '"myID-".$data->idMaterial_logs',

Submit CGridView Checked values using a form

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);
}

Categories