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
Related
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")',
),
),
),
),
));
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'];
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
<?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',
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);
}