2016-10-18 64 views
0

我有排序在列表视图yii2中的问题。我不知道如何使用独立过滤器表单创建下拉列表。yii2与下拉列表排序

在模型中,我有:

$dataProvider->sort->attributes['sort'] = [ 
      'asc' => ['game.rating' => SORT_ASC], 
      'desc' => ['game.rating' => SORT_DESC], 
     ]; 

但如何创建下拉?

型号:

class GameSearch extends Offer 
{ 

    public $status; 
    public $title; 
    public $type; 
    public $platform; 
    public $rating; 
    public $pageSize; 
    public $sort; 


    public function rules() 
    { 
     return [ 
      [['status', 'platform', 'pageSize'], 'integer'], 
      [['title', 'type', 'sort', 'rating'], 'string'] 
     ]; 
    } 

    public function search($params, $query) 
    { 
     $query->joinWith(['game', 'author']); 


     $dataProvider = new ActiveDataProvider([ 
      'query' => $query, 
      'sort' => ['defaultOrder' => ['created_at' => SORT_DESC]], 
      'pagination' => [ 
       'pageSize' => $this->pageSize, 
      ], 
     ]); 

     $dataProvider->sort->attributes['sort'] = [ 
      'asc' => ['game.rating' => SORT_ASC], 
      'desc' => ['game.rating' => SORT_DESC], 
     ]; 

     if (!($this->load($params) && $this->validate())) { 
      return $dataProvider; 
     } 

     $dataProvider->pagination->pageSize = $this->pageSize; 

     $query->andFilterWhere(['like', 'game.title', $this->title]) 
      ->andFilterWhere(['like', 'platform', $this->platform]); 

     return $dataProvider; 
    } 
} 

和我的搜索文件

<?= $form->field($model, 'sort') 
       ->dropDownList([ 
        'rating' => 'rating ASC', 
        '-rating' => 'rating DESC', 
       ]) 
       ->label(false) 
       ->error(false); 
      ?> 

回答

2

我有同样的proplem,这里是我的配置 查看。值1排序ASC和值2排序DESC来看

$findUrl = Url::current([], true); 
$pos = strpos($findUrl, '&rating'); 
if($pos){ 
    $findUrl = substr($findUrl, 0 , $pos); 
} 
$app_js = <<<JS 
    $("#find-rating1").change(function() { 
     var rating_value= $(this).val(); 
     location.href="$findUrl" +"&rating="+rating_value; 
    }); 
JS; 
$this->registerJs($app_js); 

正如你看到的,当下拉有改变事件

<?= $form->field($model, 'sort') 
      ->dropDownList([ 
       '1' => 'rating ASC', 
       '2' => 'rating DESC', 
      ],['id' =>'find-rating1']) 
      ->label(false) 
      ->error(false); 
     ?> 

,并添加js的底部。将重定向到URL将对参数1或2进行评级。因此,在Controller中,您可以获得评分值1或2并设置分类。

$ratingValue = getParam('rating', 1); 

与$ ratingValue你可以自定义搜索查询

+0

演示网址http://cubic1.jp/search/find-employees?type=1面积http://prntscr.com/cw2weu – dungphanxuan

+0

谢谢你,我会试试你的解决方案 –