我想实现一个搜索表单。我收到了搜索结果,但当请求不在表单中时,Listview会显示表格中的所有数据。
如何设置条件,以便在搜索表单为空时返回空的Listview?
型号:
public function search($params)
{
$query = Product::find();
$dataProvider = new ActiveDataProvider(['query' => $query]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere(['title' => $this->title]);
return $dataProvider;
}
控制器:
public function actionSearch()
{
$searchModel = new SearchForm();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('search', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
表格:
<div class="site-search">
<?php
$form = ActiveForm::begin([
'action' => ['search'],
'method' => 'get',])
?>
<?=$form->field($model, 'title')?>
<div class="form-group">
<?=Html::submitButton('Submit', ['class' => 'btn btn-primary'])?>
</div>
<?phpActiveForm::end();?>
</div>
视图:
<?php
echo $this->render('_form', ['model' => $searchModel]);?>
<div class="listView">
<?php
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_product',]);
?>
</div>
答案 0 :(得分:2)
您的问题可能在于搜索模型(由于缺少模型的验证规则,因此很难确切地说出来)。如果可以从$params
填充模型,则搜索功能仅设置查询条件。添加始终对查询失败的条件将解决此问题。
public function search($params)
{
if (!($this->load($params) && $this->validate())) {
$query = Product::find()->where('1 <> 1');
} else {
$query = Product::find()->where(['title' => $this->title]);
}
return new ActiveDataProvider(['query' => $query]);
}
或者,也可以返回不同类型的DataProvider:
public function search($params)
{
if (!($this->load($params) && $this->validate())) {
return new yii\data\ArrayDataProvider(['allModels' => []]);
}
$query = Product::find()->where(['title' => $this->title]);
return new ActiveDataProvider(['query' => $query]);
}
但是,如果验证失败,我仍然希望返回数据提供程序,这让我很奇怪。抛出并捕获错误并在验证失败时显示错误消息似乎是一个不错的选项,可能比仅显示空结果列表更好。