Php 如何在Yii2中显示搜索结果

Php 如何在Yii2中显示搜索结果,php,yii2,Php,Yii2,我想实现一个搜索表单。我正在获取搜索结果,但当请求不在表单中时,Listview会显示表中的所有数据 如何设置条件,以便在搜索表单为空时返回空的Listview 型号: public function search($params) { $query = Product::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); if (!($this->load($params) &&

我想实现一个搜索表单。我正在获取搜索结果,但当请求不在表单中时,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> 

视图:


您的问题可能在于搜索模型(很难得出结论,因为模型的验证规则缺失)。如果可以从
$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]);
}

然而,tt让我感到奇怪的是,如果验证失败,人们仍然希望返回数据提供者。在验证失败中抛出并捕获错误并呈现错误消息似乎是一个不错的选择,可能比只显示一个空结果列表要好。

请考虑将答案标记为接受,如果它解决了您的问题。
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]);
}
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]);
}