V
V
Victor Umansky2017-06-11 01:04:52
Yii
Victor Umansky, 2017-06-11 01:04:52

Sort goods by price, by name, etc.?

Good night everyone, tell me how to sort goods correctly, for example, by price, by name ....

$sort = [
    1 => 'От дорогих к дешевым',
    2 => 'От дешевых к дорогим',
    3 => 'популярности',
    4 => 'названию',
];
Сортировать по: <?= Html::dropDownList('', '', $sort) ?>

The names of sorting will be in a drop-down list, you can throw a code example like this, I can’t figure out how to do it ... it would be nice if you also show an example of sorting meringue without reloading the AJAX page.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-06-11
@webinar

Just like in the standard crud for gridView or listView. searchModel + activeDataProvider. Create a public variable sort in the search model, the sorting setting for the activeDataProvider depends on its value.
If it’s simple, then like this:

switch($this->sort){
  case 1:
    $order = ['price' => SORT_ASC];
    break;
  case 2:
    $order = ['price' => SORT_DESC];
    break;
  case 3:
    $order = ['rating' => SORT_ASC];
    break;
  default:
    $order = ['title' => SORT_ASC];
}
$query = MyModel::find()->where(['status' => 1]);
$provider = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
    ],
    'sort' => [
        'defaultOrder' => $order
    ],
]);

D
Dmitry, 2017-06-11
@slo_nik

Good morning.
Perhaps this widget and article will help you .
In addition to the official documentation, here is another hint that may lead you to a solution.
You can process the dropdown list like this:

$form->field($model, 'sort')->dropDownList([1 => 'От дорогих', 2 => 'От дешёвых', 3 => 'По популярности', 4 => 'По названию'],
            ['prompt' => 'Сортировать'),
             'onchange' => '
                            $.post(
                             "'.Url::toRoute('default/ajax').'",  // путь к действию контроллера
                             {id : $(this).val()}, // значение выбранного элемента списка
                             function(data){
                               $("div#city").html(data) // получение результата и подстановка в указанный div
                             }
                            )
                          '])

An action in a controller might look like this:
public function actionAjax()
{
    if(Yii::$app->request->isAjax){
      // Тут выполняете запрос к базе и возвращаете результат работы запроса.
   }
}

You need to do this in the user part of the site, as I understand it.
If in the admin panel, then based on the search model, a drop-down list for sorting in the gridView and filtering by parameter should be done.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question