Есть ли способ фильтровать результат поиска вне 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>
Вам не нужно делать вызов ajax вообще. Вы должны использовать виджет JavaScript (yiiGridView).
В моем случае мне пришлось фильтровать данные вне Gridview. Я добавил флажок для фильтрации удаленных данных. Если этот флажок установлен, удаленные данные (флаг = 1) будут перечислены, в противном случае будут перечислены все данные (флаг = 0). Рабочий пример на рисунке ниже.
Пользовательский фильтр Изображение 1
Шаг: 1 Я поставил флажок за пределами виджета сетки.
<input type="checkbox" name="ShippingChargeSearch[del_flg]" value="0" id="shippingcharge-shipping_area">
Шаг 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]"]'});
});
});
Шаг: 3 Добавлено динамическое значение параметра для запроса в файле модели ModelSearch.php (в моем случае это 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
.....
Надеюсь это поможет. Вы можете попробовать ввести текст, если хотите. Удачного кодирования!
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