使用表单提交 CGridView Checked 值
我有一个带有 CCheckBoxColumn 的 CGridView wigdet,如下所示:
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.
提前致谢.
推荐答案
您并不是绝对需要另一种形式.您可以使用附加了附加 javascript 的链接.
You do not absolutely need another form. You can just use a link with additional javascript attached to it.
要获取选中的值,可以调用javascript函数$.fn.yiiGridView.getChecked(containerID,columnID)
,参见这里,它返回一个包含 id 的数组.
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.
在您看来:
<?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>
在您的控制器中:
...
public function actionSomeaction(){
if(isset($_POST['theIds'])){
$arra=explode(',', $_POST['theIds']);
// now do something with the ids in $arra
...
}
...
}
...
你也可以使用 json 字符串,而不是简单的字符串,在我们通过 ajax 传递的数据中(从视图),但是你会使用 json_decode 而不是
(在控制器中).此外,最好在使用前验证/清理 ID.explode()
()
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.
查看文档 CHtml::ajaxLink 以了解有关 ajax 链接的更多信息.
Check out the documentation for CHtml::ajaxLink to know more about ajax links.
请注意,该示例有点粗糙,因为我还没有检查空数组的已检查 ID.
Note that the example is a little crude, since i haven't put in checks for empty array of checked ids.
相关文章