问题
There are 3 search fields in view2.php, search is working properly when i enter something into search field and hit search button. But the problem is when I hit search/Enter button without entering anything into search fields, it displays all the entries related to that model from DB.
Below is my Machine model:
public function search($params)
{
$query = Supplier::find();
$query->joinWith(['user', 'cities', 'industrialareas','supplierMachines', 'subCategory', 'types0','supplierCertificates' ]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 20,
],
]);
if (!($this->load($params) && $this->validate())) {
$query->where('1 <> 1');
}
else {
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'yoe' => $this->yoe,
]);
$query->andFilterWhere(['like', 'company_constitution', $this->company_constitution])
->andFilterWhere(['like', 'street', $this->street])
->andFilterWhere(['like', 'locality', $this->locality])
}
return $dataProvider;
}
}
machine controller which calls view2 function(it displays search fields)
public function actionView2()
{
//Display machines based on the customer search
$searchModel = new SupplierMachineSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// render
return $this->render('view2', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
View2.php
<?= $form->field($searchModel, 'enter_city')->widget(AutoComplete::classname(), [
'options' => ['placeholder' => 'Select a city ...', 'class' => 'form-control'],
'clientOptions' => [
'source' => ArrayHelper::getColumn($data, 'city_name'), ],
]) ?>
<?= $form->field($searchModel, 'enter_iarea')->widget(AutoComplete::classname(), [
'options' => ['placeholder' => 'Select a iarea ...', 'class' => 'form-control'],
'clientOptions' => [
'source' => ArrayHelper::getColumn($data1, 'iarea_name'), ],
]) ?>
<?= $form->field($searchModel, 'machine')->widget(AutoComplete::classname(), [
'options' => ['placeholder' => 'Select a iarea ...', 'class' => 'form-control'],
'clientOptions' => [
'source' => ArrayHelper::getColumn($all, 'name' ), ],
]) ?>
<?= Html::activeHiddenInput($searchModel, 'id')?>
<div class="form-group">
<?= Html::submitButton('Apply', ['class' => 'btn btn-success']) ?>
<?= Html::a('Reset', ['view2']);?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?=
ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_viewmain',
'viewParams' => [
'fullView' => false,
'context' => 'main-page',
],
]);
回答1:
Check if the search parameters, once loaded, are empty:
if ( !($this->load($params) && $this->validate()) or
(empty($this->search_param1) and empty($this->search_param2) and empty($this->search_param3)) ) {
$query->where('1 <> 1');
}
来源:https://stackoverflow.com/questions/43062117/yii2-search-with-empty-param-throws-all-records