如何在yii2中实现单个搜索表单 [英] How to implement single search form in yii2

查看:141
本文介绍了如何在yii2中实现单个搜索表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Yii2有一个 searchModel 来搜索 GridView 中的每个字段。是否可以在用户可以输入关键字的 GridView 之外创建一个搜索字段,并在搜索按钮被击中时,结果将显示在<$ c

控制器

 $ c $> GridView  >  public function actionIndex()
{
$ session = Yii :: $ app-> session;
// $ searchModel = new PayslipTemplateSearch(); ($'$'
$ b $ PayslipEmailConfig = PayslipEmailConfig :: find() - >其中(['company_id'=> new \MongoId($ session ['company_id'])]) - & ; $($'
$ b $ payslipTemplateA = PayslipTemplate :: find() - > where(['company_id'=> new \MongoId($ session ['company_id'])]) - & 'template_name'=>'A']) - > one(); $('session_ ['company_id'])]] - >和where((''template_name'= $'') >'B']) - > 1(); $($'$'
$ b $ pTemplateModel = PayslipTemplate :: find() - > where(['company_id'=> new \MongoId($ session ['company_id'])]) - > all ; $($'$')$ user = User :: find() - > where(['_ id'=> new \ MongoId($ session ['user_id'])]) - > one();
$ module_access = explode(',',$ user-> module_access);
$ b $ // dataProvider = User :: find() - >其中(['user_type'=&''BizStaff']) - >和where(['parent'=> new \\ \\MongoId($会话[ 'company_owner'])]) - >所有();
$ searchModel = new UserSearch();
$ dataProvider = $ searchModel->搜索(Yii :: $ app-> request-> queryParams);

return $ this-> render('index',[
'PayslipEmailConfig'=> $ PayslipEmailConfig,
'dataProvider'=> $ dataProvider,
'payslipTemplateA'=> $ payslipTemplateA,
'payslipTemplateB'=> $ payslipTemplateB,
'searchModel'=> $ searchModel,
]);
}
public function actionSearchresults($ keyword)
{
$ session = Yii :: $ app-> session;
if($ keyword ==''){
return $ this-> redirect(\Yii :: $ app-> request-> getReferrer()); $($ id $ b)else {
$ user = User :: find() - >其中(['_id'=> new \ MongoId($ id)]) - > one();
$ searchModel = new PayslipTemplateSearch(); $($'
$ b $ payslipTemplateA = PayslipTemplate :: find() - > where(['company_id'=> new \MongoId($ session ['company_id'])]) - & 'template_name'=>'A']) - > one(); $('session_ ['company_id'])]] - >和where((''template_name'= $'') >'B']) - > 1();
$ b $ return $ this-> render('searchresults',[
'searchModel'=> $ searchModel,
'user'=> $ user,
'payslipTemplateA'=> $ payslipTemplateA,
'payslipTemplateB'=> $ payslipTemplateB,
]);


$ / code $ / pre

我在这里提出了一个与这个问题相关的问题: a href =https://stackoverflow.com/questions/32882097/main-search-form-in-yii2> Yii2的主要搜索表单



这不是由于Kartik的 Select2 搜索下拉窗口小部件有些复杂。现在我暂时切换到一个简单的Yii2搜索字段。



VIEW

  echo $ form-> field($ model,'_id') - > textInput(array('placeholder'=>'search')) - > label(false); 

MODEL

 <?php 

namespace app \models;

使用Yii;
使用yii\base\Model;
使用yii\data\ActiveDataProvider;
使用app \models\User;

/ **
* UserSearch表示关于`app \models\User`的搜索表单后面的模型。
* /
class UserSearch extends User
{
/ **
* @inheritdoc
* /
public function rules()
{
return [
[[/ *'_ id',* /'creator_id'],'integer'],
[['fname','lname','email' ,'username','user_type'],'safe'],
];

$ b / **
* @inheritdoc
* /
公共功能场景()
{
//绕过在父类中的scenario()实现
return Model :: scenarios();
}

/ **
*使用搜索查询创建数据提供程序实例
*
* @param array $ params
*
* @return ActiveDataProvider
* /
公共函数搜索($ params)
{
$ session = Yii :: $ app-> session;

$ query = User :: find();
$ query-> where(['user_type'=&'BizStaff']) - >和where(['parent'=> new \MongoId($ session ['company_owner'])])) ;

$ dataProvider = new ActiveDataProvider([
'query'=> $ query,
]);

$ this->载入($ params);

if(!$ this-> validate()){
//如果您在验证失败时不想记录任何记录,请取消注释以下行
// $ query - 化合物其中( '0 = 1');
返回$ dataProvider;


$ query-> andFilterWhere([
'_id'=> $ this-> _id,
'creator_id'=> $ this - > creator_id,
]);

$ query-> andFilterWhere(['like','fname',$ this-> fname])
- > andFilterWhere(['like','lname', (['like','email',$ this-> email])
- > andFilterWhere(['like','username ',$ this-> username])
- >和FilterWhere(['like','user_type',$ this-> user_type]);

返回$ dataProvider;






$ b

你对如何实现一个单一搜索?这是一种更智能的搜索,因为它可以根据输入的关键字搜索数据库表中的所有内容。



编辑



当我搜索一个关键字时,比如说'hello',它会在按下回车键后给我这个URL和错误:

URL:


http://localhost/iaoy-dev/web/index.php?r = payslip-template%2Fsearchresults& PayslipTemplateSearch%5B_id%5D = hello


错误信息:


错误的请求(#400)必填参数:id

帮助。

解决方案

我有同样的问题,我的解决方案是:

模型

使用搜索参数

$ b扩展您的UserSearch模型
$ b

  class UserSearch extends User 
{
public $ searchstring;
...

启用传递变量

  public function rules()
{
return [
...
[['searchstring'],'safe '],
];

$ / code>

更改搜索方法(注意:搜索字段与 orFilterWhere ,取决于你的需求)。


$ b $

  $ query-> orFilterWhere(['like','fname',$ this-> searchstring])
- > orFilterWhere(['like','lname',$ this-> searchstring])
- > orFilterWhere(['like','email',$ this-> searchstring])
- > orFilterWhere(['like','username',$ this-> searchstring])
- > orFilterWhere(['like','user_type',$ this-> searchstring ]);

视图(也可以是布局)

使用搜索输入扩展您的表单。您可以自己设置输入字段的样式,这仅仅是一个例子:

 <?php 
/ * @var $ searchModel app \models\UserSearch * /
echo $ form-> field($ searchModel,'searchstring',[
'template'=>'< div class = input-group> {input}< span class =input-group-btn>'。
Html :: submitButton('GO',['class'=>'btn btn-default '])。
'< / span>< / div>',
]) - > textInput(['placeholder'=>'Search']);
?>

控制器

在发布表单后还要检查 $ searchstring 的值。

  {
...
$ searchModel = new UserSearch();
$ dataProvider = $ searchModel->搜索(Yii :: $ app-> request-> queryParams);
...
return $ this-> render('index',[
'searchModel'=> $ searchModel,
'dataProvider'=> $ dataProvider,
]);
}

就是这样。


Yii2 has a searchModel to search each field in the GridView. Is it possible to just create a single search field outside the GridView where the user can input keywords and by the time Search button is hit, the results will display in the GridView based on the keywords entered.

CONTROLLER

public function actionIndex()
{
    $session = Yii::$app->session;
    //$searchModel = new PayslipTemplateSearch();

    $PayslipEmailConfig = PayslipEmailConfig::find()->where(['company_id'=> new \MongoId($session['company_id'])])->one();

    $payslipTemplateA = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'A'])->one();
    $payslipTemplateB = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'B'])->one();

    $pTemplateModel = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->all();
    $user = User::find()->where(['_id' => new \MongoId($session['user_id'])])->one();
    $module_access = explode(',', $user->module_access);

    //$dataProvider = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
    $searchModel = new UserSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'PayslipEmailConfig' => $PayslipEmailConfig,
        'dataProvider' => $dataProvider,
        'payslipTemplateA' => $payslipTemplateA,
        'payslipTemplateB' => $payslipTemplateB,
        'searchModel' => $searchModel,
    ]);
}
public function actionSearchresults($keyword)
{
    $session = Yii::$app->session;
    if ( $keyword == '') {
        return $this->redirect(\Yii::$app->request->getReferrer());
    } else {
        $user = User::find()->where( [ '_id' => new \MongoId($id) ] )->one(); 
        $searchModel = new PayslipTemplateSearch();

        $payslipTemplateA = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'A'])->one();
        $payslipTemplateB = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'B'])->one();

        return $this->render('searchresults', [
            'searchModel' => $searchModel,
            'user' => $user,
            'payslipTemplateA' => $payslipTemplateA,
            'payslipTemplateB' => $payslipTemplateB,
        ]);
    }    
}

I asked a question connected to this problem here: Main Search Form in Yii2

It didn't due to some complications in Kartik's Select2 search dropdown widget. Now I switched temporarily to a simple Yii2 search field.

VIEW

echo $form->field($model, '_id')->textInput(array('placeholder' => 'search'))->label(false);

MODEL

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\User;

/**
 * UserSearch represents the model behind the search form about `app\models\User`.
 */
class UserSearch extends User
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[/*'_id',*/ 'creator_id'], 'integer'],
            [['fname', 'lname', 'email', 'username', 'user_type'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $session = Yii::$app->session;

        $query = User::find();
        $query->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            '_id' => $this->_id,
            'creator_id' => $this->creator_id,
        ]);

        $query->andFilterWhere(['like', 'fname', $this->fname])
            ->andFilterWhere(['like', 'lname', $this->lname])
            ->andFilterWhere(['like', 'email', $this->email])
            ->andFilterWhere(['like', 'username', $this->username])
            ->andFilterWhere(['like', 'user_type', $this->user_type]);

        return $dataProvider;
    }
}

Do you have any idea on how to I implement a single search? It's kind of a smarter search since it can search everything in the database table based on keywords inputted.

EDIT

When I search a keyword, say for example 'hello', it then gives me this url and error after hitting enter key:

URL:

http://localhost/iaoy-dev/web/index.php?r=payslip-template%2Fsearchresults&PayslipTemplateSearch%5B_id%5D=hello

Error message:

Bad Request (#400) Missing required parameters: id

Help.

解决方案

I had the same problem and my solution is:

Model

Extend your UserSearch Model with a search parameter

class UserSearch extends User
{
    public $searchstring;
    ...

Enable passing the variable

    public function rules()
    {
        return [
            ...
            [['searchstring'], 'safe'],
        ];
    }

Change your search-Method (beware: the searchfields are combined with orFilterWhere, depends on your needs).

     $query->orFilterWhere(['like', 'fname', $this->searchstring])
        ->orFilterWhere(['like', 'lname', $this->searchstring])
        ->orFilterWhere(['like', 'email', $this->searchstring])
        ->orFilterWhere(['like', 'username', $this->searchstring])
        ->orFilterWhere(['like', 'user_type', $this->searchstring]);

View (could be also layout)

Extend your form with a search-input. You can style the input-field by yourself, this is just an example:

<?php
/* @var $searchModel app\models\UserSearch */
echo $form->field($searchModel, 'searchstring', [
        'template' => '<div class="input-group">{input}<span class="input-group-btn">' .
        Html::submitButton('GO', ['class' => 'btn btn-default']) .
        '</span></div>',
    ])->textInput(['placeholder' => 'Search']);
?>

Controller

Also check for the value of $searchstring after posting the form.

public function actionIndex()
{
    ...
    $searchModel = new UserSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    ...
    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

That's it.

这篇关于如何在yii2中实现单个搜索表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆