咱們在用表格展現數據並管理的時候,可能會須要用到按鈕來操做某一行數據,好比查看,修改,刪除!php
Yii內置了3種按鈕:查看,修改和刪除,你能夠自定義樣式、事件。詳細配置見類參考:CButtonColumn.html
若是須要自定義按鈕綁定指定的事件該怎麼辦呢?ajax
幸運的是Yii提供了自定義按鈕的辦法.看代碼:express
在視圖文件裏面:安全
$this->widget('zii.widgets.grid.CGridView', array( 'id'=>'xx-xx-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'pager'=>array( 'class'=>'CLinkPager', 'nextPageLabel'=>'下一頁', 'prevPageLabel'=>'上一頁', 'header'=>'', ), 'summaryText'=>'<font color=#0066A4>顯示{start}-{end}條.共{count}條記錄,當前第{page}頁</font>', 'columns'=>array( array( 'name'=>'id', 'htmlOptions'=>array('width'=>'25'), 'sortable'=>false, ), array( 'class'=>'CButtonColumn', 'template'=>'{view} {update}', 'viewButtonOptions'=>array('title'=>'查看'), 'updateButtonOptions'=>array('title'=>'修改'), ), array( 'class'=>'CButtonColumn', 'header'=>'首頁展現', 'template'=>'{add} {del}', 'buttons'=>array( 'add' => array( 'label'=>'展現', // text label of the button 'url'=>'Yii::app()->controller->createUrl("focus/create",array("id"=>$data->primaryKey,"type"=>1))', // a PHP expression for generating the URL of the button 'imageUrl'=>'http://s.maylou.com/common/images/ysh.jpg', // image URL of the button. If not set or false, a text link is used 'options'=>array('style'=>'cursor:pointer;'), // HTML options for the button tag 'click'=>$click, // a JS function to be invoked when the button is clicked 'visible'=>'SiteRecommend::isItemInTypeAndId(1, $data->id)?false:true', ), 'del' => array( 'label'=>'取消展現', // text label of the button 'url'=>'Yii::app()->controller->createUrl("focus/delete",array("id"=>$data->primaryKey,"type"=>1))', // a PHP expression for generating the URL of the button 'imageUrl'=>'http://s.maylou.com/common/images/yzhu.jpg', // image URL of the button. If not set or false, a text link is used 'options'=>array('style'=>'cursor:pointer;'), // HTML options for the button tag 'click'=>$click, // a JS function to be invoked when the button is clicked 'visible'=>'SiteRecommend::isItemInTypeAndId(1, $data->id)?true:false', ) ), ), ), ));
buttons選項提供了建立按鈕的方法,上面建立了2個按鈕:add和del,並註冊到template裏面。其中最主要的是click選項,決定了你的觸發條件。這裏用ajax觸發。在上面的代碼前面加上$click內容:app
$csrfTokenName = Yii::app()->request->csrfTokenName; $csrfToken = Yii::app()->request->csrfToken; $csrf = "\n\t\tdata:{ '$csrfTokenName':'$csrfToken' },"; $Confirmation= "你肯定要這麼作?"; $afterDelete = 'function(link,success,data){ if(success) alert(data); }'; $click=<<<EOD function() { if(!confirm("$Confirmation")) return false;; var th=this; var afterDelete=$afterDelete; $.fn.yiiGridView.update('build-oneprice-grid', { type:'POST', url:$(this).attr('href'),$csrf success:function(data) { $.fn.yiiGridView.update('build-oneprice-grid'); afterDelete(th,true,data); }, error:function(XHR) { return afterDelete(th,false,XHR); } }); return false; } EOD;
csrf不用管他,是安全驗證,必需要有,不然會400報錯.$click是js函數的字符竄,用了文檔字符竄形式,注意結束的EOD前面必須沒空格,也不能縮進。yii
這是Yii內置的yiiGridView Jquery插件,把請求提交到控制器的動做裏面處理,而後返回結果並顯示。最後還會更新一次gridview.