首先实现搜索框,这里自定义了Widget
use Yii;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
class GridViewSearch extends \yii\bootstrap\Widget {
public $searchOptions = []; // ['name' => ['type' => 'text', 'value' => 值, 'placeholder' => 多语言app.php中的key], 'name' => ['type' => 'select', 'data' => 下拉数据, 'value' => 值] ]
public $postUrl = ''; //'product/index'
public function run() {
$formStart = Html::beginForm([$this->postUrl] , 'GET', ['class' => 'form-inline']);
$itemGroup = $this->createItems();
$formSubmit = Html::submitButton(Yii::t('backend', 'search'), ['class' => 'btn btn-success']);
$formEnd = Html::endForm();
return Html::tag('div', $formStart . $itemGroup . $formSubmit . $formEnd, ['class' => 'content-search']);
}
/*<div class="content-search">
<?= Html::beginForm(['order/update'], 'post', ['class' => 'form-inline']) ?>
<div class="form-group"><?= Html::input('text', 'username', '', ['class' => 'form-control']) ?></div>
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
<?= Html::endForm() ?>
</div>*/
private function createItems() {
// 搜索允许 text select date
$itemGroup = '';
foreach($this->searchOptions as $key => $val) {
$type = $val['type'];
$value = '';
if(isset($val['value'])) {
$value = $val['value'];
}
if($type == 'date') {
// 后期扩展
} else if($type == 'select') {
$item = Html::dropDownList($key, $value, $val['data'], ['class' => 'form-control']);
} else {
$item = Html::input('text', $key, $value, ['class' => 'form-control', 'placeholder' => Yii::t('backend', $val['placeholder'])]);
}
$itemGroup .= Html::tag('div', $item, ['class' => 'form-group']);
}
return $itemGroup;
}
}
使用方法
GridViewSearch::widget([
'postUrl' => 'product/index',
'searchOptions' => [
'name' => ['type' => 'text', 'value' => $searchQuery['name'], 'placeholder' => 'search_classhour_name'],
'status' => ['type' => 'select', 'data' => $statusArr, 'value' => $searchQuery['status']],
'type' => ['type' => 'select', 'data' => $typesArr, 'value' => $searchQuery['type']],
]
]);
后台
$model = new Product();
$statusArr = $model->listStatus();
$typesArr = $model->listTypes();
$query = Product::find();
$searchQuery = [];
$name = Yii::$app->request->get('name');
$searchQuery['name'] = $name;
if(!empty($name)) {
$query->andFilterWhere(['like', 'name', $name]);
}
// 按状态
$status = Yii::$app->request->get('status');
$searchQuery['status'] = $status;
if(!empty($status)) {
$query->andFilterCompare('status', $status);
}
// 按类型
$type = Yii::$app->request->get('type');
$searchQuery['type'] = $type;
if(!empty($type)) {
$query->andFilterCompare('type', $type);
}
$dataProvider = new ActiveDataProvider([
'query' =>$query,
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
'statusArr' => $statusArr,
'typesArr' => $typesArr,
'searchQuery' => $searchQuery,
]);