首页 > 解决方案 > 在可排序网格行为中添加项目

问题描述

我使用可排序网格行为,当我尝试添加项目时,我的排序属性有问题“正在执行的 SQL 是:SELECT MAX”

 public function behaviors()
{
    return [
      'sort' => [
        'class' => SortableGridBehavior::class,
        'sortableAttribute' => 'sort'
      ],
   ];
}

我在控制器中的操作

public function actionAddLibraryValue($libId)
{
    $request = Yii::$app->request;
    $model = new LibrariesValues();
    $model->lib_id = $libId;

    if ($request->isPjax && $request->isPost && $model->load($request->post()) && $model->validate()) {
        try {
            $model->save();
        } catch (\Exception $e) {
            print_r($e);exit;
        }
    }
 }

标签: phpyii2

解决方案


小部件似乎有问题,我重新定义了类方法,现在可以工作了

 class CustomSortableGrid extends SortableGridBehavior
 {
    public function beforeInsert()
    {
    /** @var ActiveRecord $model */
    $model = $this->owner;
    if (!$model->hasAttribute($this->sortableAttribute)) {
        throw new InvalidConfigException("Invalid sortable attribute `{$this->sortableAttribute}`.");
    }

    $query = $model::find();
    if (is_callable($this->scope)) {
        call_user_func($this->scope, $query);
    }

    /* Override model alias if defined in the model's class */
    $query->from([$model::tableName()]);

    $maxOrder = $query->max('{{' . trim($model::tableName(), '{}') . '}}.[[' . $this->sortableAttribute . ']]');
    $model->{$this->sortableAttribute} = $maxOrder + 1;
}
}

推荐阅读