2015-07-06 4 views
1

Есть ли способ фильтрации результатов поиска вне gridview? Я хочу сделать это, потому что для меня почти невозможно сделать обычай выглядеть с сеткой по умолчанию.Yii2 - фильтр результатов поиска вне gridview

Это метод я использую для поиска:

public function actionSell() 
    { 
     $searchModel = new ProductsSearch(); 
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams); 

     if(Yii::$app->request->isAjax): 

      echo json_encode($dataProvider); 

      return true; 

     endif; 

     return $this->render('sell', [ 
       'searchModel' => $searchModel, 
       'dataProvider' => $dataProvider 
      ]); 
    } 

Метод поиска:

public function search($params) 
    { 
     $query = Products::find(); 

     $dataProvider = new ActiveDataProvider([ 
      'query' => $query, 
     ]); 

     $this->load($params); 

     if (!$this->validate()) { 
      // uncomment the following line if you do not want to return any records when validation fails 
      // $query->where('0=1'); 
      return $dataProvider; 
     } 

     $query->andFilterWhere([ 
      'id'      => $this->id, 
      'user_id'    => $this->user_id, 
      'your_price'    => $this->your_price, 
      'available_stock'  => $this->available_stock, 
      'shipping_costs_carrier' => $this->shipping_costs_carrier, 
      'shipping_costs_type' => $this->shipping_costs_type, 
      'shipping_costs_cost' => $this->shipping_costs_cost, 
     ]); 

     $query->andFilterWhere(['like', 'inci', $this->inci]) 
      ->andFilterWhere(['like', 'inn', $this->inn]) 
      ->andFilterWhere(['like', 'fe', $this->fe]) 
      ->andFilterWhere(['like', 'n_cas', $this->n_cas]) 
      ->andFilterWhere(['like', 'einecs', $this->einecs]) 
      ->andFilterWhere(['like', 'iupac', $this->iupac]) 
      ->andFilterWhere(['like', 'restriction', $this->restriction]) 
      ->andFilterWhere(['like', 'function', $this->function]) 
      ->andFilterWhere(['like', 'trade_name', $this->trade_name]) 
      ->andFilterWhere(['like', 'inci_name', $this->inci_name]) 
      ->andFilterWhere(['like', 'component_1', $this->component_1]) 
      ->andFilterWhere(['like', 'component_2', $this->component_2]) 
      ->andFilterWhere(['like', 'country_id', $this->country_id]) 
      ->andFilterWhere(['like', 'state_id', $this->state_id]) 
      ->andFilterWhere(['like', 'address', $this->address]); 

     return $dataProvider; 
    } 

JS код для функциональности AJAX:

$('#product-sell-search').on('submit', function(){ 

     var form = $(this); 

     $.ajax({ 
       url: form.attr('action'), 
       type: 'get', 
       dataType: 'json', 
       data: form.serialize(), 
       success: function(data) { 
         console.log(data); 
       } 
     }); 

     return false; 

    }); 

Форма в виде:

<form action="/products/sell" method="get" class="form-inline" id=product-sell-search accept-charset="utf-8" role=form> 

       <div class="form-group"> 

        <label for="product">Your product name</label> 

        <input type="text" class="form-control product-name" name="ProductsSearch[inci]" placeholder="Search products..." > 
       </div> 

       <button type="submit" class="btn btn-black">Search</button> 

      </form> 
+0

так что не работает? фильтр не применяется? – Tony

+0

Не знаю: /. Возвращенные данные отображаются как построитель запросов из метода поиска, а фактические данные из db (я не обновлял вопрос с помощью метода поиска). – Sasha

ответ

0

DataProvider - это не сами данные, это своего рода обертка вокруг данных, которую вы получите после вызова метода getModels(). Если вы хотите использовать json_decode добавить это в ваш search метод:

//your filters above 
if(Yii::$app->request->isAjax) { 
    $query->asArray(); 
} 

return $dataProvider; 

и в actionSell():

if(Yii::$app->request->isAjax) { 
    echo json_encode($dataProvider->getModels()); 
    return true; 
} 

Код делает следующее: если вы запросили данные с помощью AJAX, он будет возвращать все модели как массивы, когда вы назовете $dataProvider->getModels(), и после этого они будут закодированы json