使用 EditableColumn 在 Gridview 中更新一个原始单元格中的两个单元格

Update two cells in one raw in Gridview using EditableColumn

我在我的 Yii2 应用程序中有一个可编辑的 GridView,并使用 kartik EditableColumn。当只有一个可编辑列时,一切正常,但是当我尝试添加一个可编辑列时,它会保存 Price 列的编辑值并将 [ 的值设置为零=26=] 列。相反的方式相同(如果更新 expire_days 它保存值但将 Price 值设置为零)。

观点:

'columns' => [
    [
        'class'=>'kartik\grid\EditableColumn',
        'attribute' => 'price',
        'editableOptions'=>[
            'header'=>' ',                         
            'inputType'=>\kartik\editable\Editable::INPUT_SPIN,
            'options'=>['pluginOptions'=>['min'=>0, 'max'=>5000000]]
        ],
        'value' => function ($model) {
            return $model->price;
         },
        'filter' => Category::getPrices(),
        'format' => 'raw'
    ],


    [
        'class'=>'kartik\grid\EditableColumn',
        'attribute' => 'expire_days',
        'editableOptions'=>[
            'header'=>' ',
            'inputType'=>\kartik\editable\Editable::INPUT_SPIN,
            'options'=>['pluginOptions'=>['min'=>0, 'max'=>100]]
         ],
        'value' => function ($model) {
            return $model->expire_days;
         },
        'filter' => Category::getExpDays(),
        'format' => 'raw'
    ],                                         
]

控制器:

if (Yii::$app->request->post('hasEditable')) {
    $model = new Category();
    $id = Yii::$app->request->post('editableKey');
    $model = Category::findOne($id);
    $out = Json::encode(['output'=>'', 'message'=>'']);

    $post = [];
    $posted = current($_POST['Category']);
    $post['Category'] = $posted;

    if ($model->load($post)) {
        $model->price = $post['Category']['price'];
        $model->expire_days = $post['Category']['expire_days'];
        $model->save();
        $output = '';
        $out = Json::encode(['output'=>$output,'message'=>'']);
    }

    echo $out;
    return;
}

你应该分别处理两种情况:

if ($model->load($post)) {
    if ($post['Category'] && $post['Category']['price']) {
        $model->price = $post['Category']['price'];
    }

    if ($post['Category'] && $post['Category']['expire_days']) {
        $model->expire_days = $post['Category']['expire_days'];
    }
    $model->save();
    $output = '';
    $out = Json::encode(['output'=>$output,'message'=>'']);
}

如果您收到价格 - 您只更新价格。如果您收到 expire_days - 更新 expire_days.