When data needs to be sorted according to one or several attributes, we can use Sort to represent the sorting information and generate appropriate hyperlinks that can lead to sort actions. A typical usage example is as follows, ~~~ function actionIndex() { $sort = new Sort([ 'attributes' => [ 'age', 'name' => [ 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC], 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC], 'default' => SORT_DESC, 'label' => 'Name', ], ], ]); $models = Article::find() ->where(['status' => 1]) ->orderBy($sort->orders) ->all(); return $this->render('index', [ 'models' => $models, 'sort' => $sort, ]); } ~~~ View: ~~~ display links leading to sort actions echo $sort->link('name') . ' | ' . $sort->link('age'); foreach ($models as $model) { display $model here } ~~~ In the above, we declare two [[attributes]] that support sorting: name and age. We pass the sort information to the Article query so that the query results are sorted by the orders specified by the Sort object. In the view, we show two hyperlinks that can lead to pages with the data sorted by the corresponding attributes.
Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Inheritance: extends yii\base\Object
コード例 #1
0
ファイル: SortTest.php プロジェクト: sciurodont/yii2
 public function testLink()
 {
     $this->mockApplication();
     $manager = new UrlManager(['baseUrl' => '/index.php', 'cache' => null]);
     $sort = new Sort(['attributes' => ['age', 'name' => ['asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC], 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC]]], 'params' => ['sort' => 'age,-name'], 'enableMultiSort' => true, 'urlManager' => $manager, 'route' => 'site/index']);
     $this->assertEquals('<a class="asc" href="/index.php?r=site%2Findex&amp;sort=-age%2C-name" data-sort="-age,-name">Age</a>', $sort->link('age'));
 }
コード例 #2
0
 public function __construct($id, $controller, $config = [])
 {
     parent::__construct($id, $controller, $config);
     if (is_array($this->sort) && !isset($this->sort["class"])) {
         $this->sort["class"] = Sort::className();
         $this->sort = \Yii::createObject($this->sort);
     }
     if ($this->sort == null) {
         $this->sort = \Yii::createObject(Sort::className());
     }
     if ($this->searchModelClass == null && class_exists($this->modelClass . "Search")) {
         $this->searchModelClass = $this->modelClass . "Search";
     }
 }
コード例 #3
0
ファイル: ArrayHelperTest.php プロジェクト: howq/yii2
 public function testMultisortUseSort()
 {
     // single key
     $sort = new Sort(['attributes' => ['name', 'age'], 'defaultOrder' => ['name' => SORT_ASC]]);
     $orders = $sort->getOrders();
     $array = [['name' => 'b', 'age' => 3], ['name' => 'a', 'age' => 1], ['name' => 'c', 'age' => 2]];
     ArrayHelper::multisort($array, array_keys($orders), array_values($orders));
     $this->assertEquals(['name' => 'a', 'age' => 1], $array[0]);
     $this->assertEquals(['name' => 'b', 'age' => 3], $array[1]);
     $this->assertEquals(['name' => 'c', 'age' => 2], $array[2]);
     // multiple keys
     $sort = new Sort(['attributes' => ['name', 'age'], 'defaultOrder' => ['name' => SORT_ASC, 'age' => SORT_DESC]]);
     $orders = $sort->getOrders();
     $array = [['name' => 'b', 'age' => 3], ['name' => 'a', 'age' => 2], ['name' => 'a', 'age' => 1]];
     ArrayHelper::multisort($array, array_keys($orders), array_values($orders));
     $this->assertEquals(['name' => 'a', 'age' => 2], $array[0]);
     $this->assertEquals(['name' => 'a', 'age' => 1], $array[1]);
     $this->assertEquals(['name' => 'b', 'age' => 3], $array[2]);
 }
コード例 #4
0
 /**
  * Sorts the data models according to the given sort definition
  *
  * @param array $models the models to be sorted
  * @param \yii\data\Sort  $sort   the sort definition
  *
  * @return array the sorted data models
  */
 protected function sortModels($models, $sort)
 {
     $orders = $sort->getOrders();
     if (!empty($orders)) {
         ArrayHelper::multisort($models, array_keys($orders), array_values($orders));
     }
     return $models;
 }
コード例 #5
0
ファイル: SearchForm.php プロジェクト: platx/yii2-rest
 /**
  * @inheritdoc
  */
 public function setSort($value)
 {
     if (is_array($value)) {
         $config = ['class' => Sort::className(), 'enableMultiSort' => $this->enableMultiSort];
         $this->_sort = Yii::createObject(array_merge($config, $value));
     } elseif ($value instanceof Sort || $value === false) {
         $this->_sort = $value;
     } else {
         throw new InvalidParamException('Only Sort instance, configuration array or false is allowed.');
     }
     if (($sort = $this->getSort()) !== false && $this->query instanceof ActiveQueryInterface) {
         /* @var $model Model */
         $model = new $this->query->modelClass();
         if (empty($sort->attributes)) {
             foreach ($model->attributes() as $attribute) {
                 $sort->attributes[$attribute] = ['asc' => [$attribute => SORT_ASC], 'desc' => [$attribute => SORT_DESC], 'label' => $model->getAttributeLabel($attribute)];
             }
         } else {
             foreach ($sort->attributes as $attribute => $config) {
                 if (!isset($config['label'])) {
                     $sort->attributes[$attribute]['label'] = $model->getAttributeLabel($attribute);
                 }
             }
         }
     }
 }
コード例 #6
0
ファイル: Html.php プロジェクト: kalibao/magesko
 /**
  * Generates a hyperlink that can be clicked to cause sorting.
  * @param Sort $sort the current Sort instance
  * @param string $attribute the attribute name
  * @param array $options additional HTML attributes for the hyperlink tag.
  * There is one special attribute `label` which will be used as the label of the hyperlink.
  * If this is not set, the label defined in [[attributes]] will be used.
  * If no label is defined, [[\yii\helpers\Inflector::camel2words()]] will be called to get a label.
  * Note that it will not be HTML-encoded.
  * @return string
  */
 public static function sortLink(Sort $sort, $attribute, $options = [])
 {
     if (($direction = $sort->getAttributeOrder($attribute)) !== null) {
         $class = $direction === SORT_DESC ? 'current-sort desc' : 'current-sort asc';
         $icon = $direction === SORT_DESC ? 'glyphicon-sort-by-alphabet-alt' : 'glyphicon-sort-by-alphabet';
         if (isset($options['class'])) {
             $options['class'] .= ' ' . $class;
         } else {
             $options['class'] = $class;
         }
     } else {
         $icon = 'glyphicon-sort-by-alphabet';
         if (isset($options['class'])) {
             $options['class'] .= ' asc';
         } else {
             $options['class'] = 'asc';
         }
     }
     $url = $sort->createUrl($attribute);
     $options['data-sort'] = $sort->createSortParam($attribute);
     if (isset($options['label'])) {
         $label = $options['label'];
         unset($options['label']);
     } else {
         if (isset($sort->attributes[$attribute]['label'])) {
             $label = $sort->attributes[$attribute]['label'];
         } else {
             $label = Inflector::camel2words($attribute);
         }
     }
     $label .= ' <span class="glyphicon ' . $icon . '"></span>';
     return Html::a($label, $url, $options);
 }
コード例 #7
0
 /**
  * Sets the sort definition for this data provider.
  * @param array|Sort|boolean $value the sort definition to be used by this data provider.
  * This can be one of the following:
  *
  * - a configuration array for creating the sort definition object. The "class" element defaults
  *   to 'yii\data\Sort'
  * - an instance of [[Sort]] or its subclass
  * - false, if sorting needs to be disabled.
  *
  * @throws InvalidParamException
  */
 public function setSort($value)
 {
     if (is_array($value)) {
         $config = ['class' => Sort::className()];
         if ($this->id !== null) {
             $config['sortVar'] = $this->id . '-sort';
         }
         $this->_sort = Yii::createObject(array_merge($config, $value));
     } elseif ($value instanceof Sort || $value === false) {
         $this->_sort = $value;
     } else {
         throw new InvalidParamException('Only Sort instance, configuration array or false is allowed.');
     }
 }
コード例 #8
0
ファイル: SearchTrait.php プロジェクト: maybeworks/yii2-libs
 /**
  * Имя класса сортировки
  * @return string
  */
 public function sortClassName()
 {
     return Sort::className();
 }