Yii2 - 过滤gridview外的搜索结果

Is there a way to filter search result outside the gridview? I want to do this, because it is near impossible for me to make custom look with the default grid.

This is method I use for searching:

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
            ]);
    }

Search method:

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;
    }

The JS code for AJAX functionality:

$('#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 in the view:

<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>

DataProvider is not the data itself, it is sort of wrapper around the data, that you will receive after calling getModels() method. If you want to use json_decode add this into your search method:

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

return $dataProvider;

and in actionSell():

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

The code does following: if you requested your data with ajax, it will return all models as arrays when you will call $dataProvider->getModels() and after that they will be json-encoded

You don't need to make ajax call whatsoever. You have to use the javascript widget (yiiGridView).

In my case, I had to filter data outside of Gridview. I added a checkbox to filter deleted data. If checked, deleted data (flag=1) will be listed else all data (flag=0) will be listed. Working example is in the image below.

Custom Filter Image 1

Custom Filer Image 2

Step : 1 I put the checkbox outside of the gridview widget.

<input type="checkbox" name="ShippingChargeSearch[del_flg]" value="0" id="shippingcharge-shipping_area">

Step: 2

$(function(){
        $('#shippingcharge-shipping_area').click(function(e) {
            var chkVal = $(this).prop('checked');
            if(chkVal) {
                $('input[name="ShippingChargeSearch[del_flg]"]').val(1);
            }else{
                $('input[name="ShippingChargeSearch[del_flg]"]').val(0);
            }

        $('#w1').yiiGridView({'filterUrl':'/ec-admin/shipping-charge/index','filterSelector':'input[name="ShippingChargeSearch[del_flg]"]'});
        });
    });

Step : 3 Added dynamic param value to query in ModelSearch.php model file (in my case that is ShippingChargeSearch.php)

 /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params,$querys=null)
    {
        $delFlg = isset($params['ShippingChargeSearch']['del_flg']) ? $params['ShippingChargeSearch']['del_flg'] : 0;
        $query = ShippingCharge::find()
                    ->alias('t')
                    ->where(['del_flg'=>$delFlg]);
        if(!empty($querys)){
           $query->andWhere($querys);
        }
        // add conditions that should always apply here
.....

Image for Step 3

Hope this helps. You can try with input text if you want. Happy Coding!