Tabular Input and Custom SortOrder

I have followed the guide on tabular input: http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html

I have set up my tabular form so that the items can be sorted (using jQuery UI sortable plugin).

Now when I Submit the form, I want to be able to assign the custom sort order to each item. But I am struggling to find out how to get the correct index of each item.

Controller:




public function actionUpdate()

{

    $items = Product::find()->indexBy('id')->all();


    if (Model::loadMultiple($items, Yii::$app->request->post()) && Model::validateMultiple($items)) {

        foreach ($items as $item) {

            // HERE I want to store the sort order value

            $item->sort_order = <SORT ORDER VALUE>;


            $item->save(false);

        }

        return $this->redirect('index');

    }


    return $this->render('update', ['items' => $items]);

}



View:




<?php $form = ActiveForm::begin(); ?>


<div class="sortable">

    <?php foreach ($items as $index => $value) : ?>

        <div class="item">

            <?php echo $form->field($value, "[$index]name"); ?>

        </div>

    <?php endforeach; ?>

</div>


<?= Html::submitButton('Save Changes', ['class' => 'btn btn-success']) ?>


<?php ActiveForm::end(); ?>



The following should work for a very simple situation:




public function actionUpdate()

{

    $items = Product::find()->addOrderBy(['sort_order'=>SORT_ASC])->indexBy('id')->all();


    if (Model::loadMultiple($items, Yii::$app->request->post()) && Model::validateMultiple($items)) {

        $n = 0;

        foreach ($items as $item) {

            // HERE I want to store the sort order value

            $item->sort_order = $n++;

            $item->save(false);

        }

        return $this->redirect('index');

    }


    return $this->render('update', ['items' => $items]);

}



But when the number of items get larger, then you would want to paginate and/or filter the items in the view using a GridView instead of a simple table. Then things would get a little more complicated.

The following wiki was written for Yii 1.1.x sometimes ago, but I hope you’ll get some hints from it.

http://www.yiiframework.com/wiki/238/creating-a-jqueryui-sortable-cgridview