我在yii中使用checkbox
中的CgridView
时尝试将值传递给js函数时遇到了问题。用户界面如下所示:
我希望当我单击复选框时,应该调用javascript函数来更新数据库中的数据,如下所示:
(example : 'onclick'=> "fn_onclick($data->id);")
但是,看起来它不起作用。
代码:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'assign-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'header'=>'is_admin',
'name'=>'check',
'id'=>'select',
'class'=>'CCheckBoxColumn',
'checked'=>'0',
'htmlOptions'=>array(
'style'=>'text-align: center',
'onclick'=> "fn_onclick($data->id);"
),
)
?>
答案 0 :(得分:0)
究竟什么不起作用?
onLlick属性未被evaluateExpression函数解析,就像您在此处看到的那样https://github.com/yiisoft/yii/blob/1.1.17/framework/zii/widgets/grid/CCheckBoxColumn.php#L220
所以你应该以不同的方式解决这个问题。或者扩展CCheckBoxColumn并添加你自己的功能
$rawData = [
['id'=>1,'email'=>'foo','username'=>'foo@bar.nl','is_admin'=>0],
['id'=>2,'email'=>'bar','username'=>'bar@foo.nl','is_admin'=>0],
['id'=>3,'email'=>'foobar','username'=>'foobar@barfoo.nl','is_admin'=>0]
];
$dataProvider=new CArrayDataProvider($rawData, array(
'id'=>'user',
'sort'=>array(
'attributes'=>array(
'id', 'username', 'email',
),
),
'pagination'=>array(
'pageSize'=>10,
),
));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'assign-grid',
'dataProvider'=>$dataProvider,
'selectionChanged' => 'js:function() { selectionChanged() }', // listen to selection changed
'rowHtmlOptionsExpression' => 'array("id"=>"row-".$data["id"],"data-username"=>$data["username"])', // if you're using a object this should be $data->id
'columns'=>array(
'id',
'username',
'email',
array(
'header'=>'is_admin',
'name'=>'check',
'id'=>'select',
'class'=>'CCheckBoxColumn',
'checked'=>'0',
'htmlOptions'=>array(
'style'=>'text-align: center',
),
),
),
));
?>
<script type="application/javascript">
function selectionChanged(){
var ids = $('#assign-grid').yiiGridView('getChecked', 'select');
for (i = 0; i < ids.length; i++) {
var id = ids[i];
console.log("user: "+ $('#row-'+id).attr('data-username') + " is admin"); // retrieve the data attribute
}
}
</script>
更新,以便标题不会成为复选框
class ECheckBoxColumn extends CCheckBoxColumn
{
//...
public $headerCheckbox = false;
//...
public function getHeaderCellContent()
{
if(trim($this->headerTemplate)==='')
return $this->grid->blankDisplay;
if($this->selectableRows===null && $this->grid->selectableRows>1 && $this->$headerCheckbox)
$item=CHtml::checkBox($this->id.'_all',false,array('class'=>'select-on-check-all'));
elseif($this->selectableRows>1 && $this->$headerCheckbox)
$item=CHtml::checkBox($this->id.'_all',false);
else
$item=parent::getHeaderCellContent();
return strtr($this->headerTemplate,array(
'{item}'=>$item,
));
}
}