GridView直接更新数据,kartik\grid\EditableColumn用法 [ 2.0 版本 ]
视图的_columns.php文件,这里用到的是crudajax生成的
<?php
use yii\helpers\Url;
use common\models\ProductCategory;
return [
[
'class' => 'kartik\grid\SerialColumn',
'width' => '30px',
],
[
//'class' => '\kartik\grid\DataColumn',
'attribute' => 'name',
'class' => '\kartik\grid\EditableColumn',
],
[
'class' => '\kartik\grid\DataColumn',
'attribute' => 'category.name',
],
[
'class' => '\kartik\grid\EditableColumn',
'attribute' => 'price',
],
'created_at:datetime',
[
'class' => 'kartik\grid\ActionColumn',
'dropdown' => false,
'vAlign' => 'middle',
'urlCreator' => function ($action, $model, $key, $index) {
return Url::to([$action, 'id' => $key]);
},
'header' => Yii::t('app', '操作'),
'viewOptions' => ['role' => 'modal-remote', 'title' => 'View', 'data-toggle' => 'tooltip'],
'updateOptions' => ['role' => 'modal-remote', 'title' => 'Update', 'data-toggle' => 'tooltip'],
'deleteOptions' => ['role' => 'modal-remote', 'title' => 'Delete',
'data-confirm' => false, 'data-method' => false,// for overide yii data api
'data-request-method' => 'post',
'data-toggle' => 'tooltip',
'data-confirm-title' => Yii::t('app', '操作确认'),
'data-confirm-message' => Yii::t('app', '你确定要删除这个选项吗?')],
],
];
在控制器index方法里加上一段
/**
* Lists all Product models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new ProductSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if ($this->isAjax && Yii::$app->request->post('hasEditable')) {
Yii::$app->response->format = Response::FORMAT_JSON;
$model = Product::findOne($this->post['editableKey']);
$out = ['output' => '', 'message' => ''];
$this->post[$model->formName()] = $this->post[$model->formName()][$this->post['editableIndex']];
if ($model->load($this->post)) {
// can save model or do something before saving model
if($model->save()) {
$output = '';
/*if (isset($this->post[$model->formName()]['price_cny'])) {
$output = Yii::$app->formatter->asDecimal($model->price, 2);
}*/
$out = ['output' => $output, 'message' => ''];
}else{
$out['message'] = $model->getErrors();
}
}else{
$out['message'] = $model->getErrors();
}
return $out;
}
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
基中的$this->isAjax和$this->post,是我在基类定义好了的,同学们可以改为自己的
下面是效果图
---错误 (#8): 服务器内部错误。图片弄不了
如果需要做权限控制之类的,修改提交地址不想直接放在index方法,可以自定义提交地址,加上editableOptions参数即可
[
//'class' => '\kartik\grid\DataColumn',
'class' => '\kartik\grid\EditableColumn',
'attribute' => 'price',
'editableOptions'=> function ($model, $key, $index) {
return [
//'size'=>'sm',
'formOptions' => [
'method'=>'post',
'action' => ['editable']
]
];
}
],
shuliangfu 广西桂林
注册时间:2015-05-07
最后登录:2019-05-17
在线时长:455小时13分
最后登录:2019-05-17
在线时长:455小时13分
- 粉丝7
- 金钱12090
- 威望10
- 积分16740
共 2 条评论
竟然没有评论,不错哦
问下,kartik\grid\EditableColumn 在Grid里点击时弹出的是input,能改成textarea吗?