Yii Framework Forum: Tabular Input and Custom SortOrder - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Tabular Input and Custom SortOrder

#1 User is offline   GSTAR 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 1,053
  • Joined: 30-October 09

Posted 03 November 2017 - 02:59 PM

I have followed the guide on tabular input: http://www.yiiframew...ular-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(); ?>

0

#2 User is offline   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 3,373
  • Joined: 16-February 11
  • Location:Japan

Posted 03 November 2017 - 06:08 PM

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.yiiframew...table-cgridview
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users