我的Yii2项目遇到了另一个虚拟问题。我在视图中有一个标准的gridView,定义为:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout' => '{items}{summary}',
'columns' => [
[
'class' => 'yii\grid\SerialColumn',
'contentOptions' => [
'style' => 'vertical-align: middle;'
]
],
[
'attribute' => 'name',
],
[
'attribute' => 'type',
'value' => function($model){
/* @var $model app\models\Object */
return $model->typeNames()[$model->type];
},
'filter' => Select2::widget([
'name' => 'ObjectSearch[type]',
'data' => Object::typeNames(),
'theme' => Select2::THEME_BOOTSTRAP,
'hideSearch' => true,
'options' => [
'placeholder' => 'Wybierz typ obiektu...',
'value' => isset($_GET['ObjectSearch[type]']) ? $_GET['ObjectSearch[type]'] : null
]
]),
],
[
'attribute' => 'countryId',
'value' => 'country.name',
'filter' => Select2::widget([
'name' => 'ObjectSearch[countryId]',
'data' => Country::forWidgets(),
'theme' => Select2::THEME_BOOTSTRAP,
'options' => [
'placeholder' => 'Wybierz państwo...'
]
]),
],
//other columns
],
]); ?>
我已经定义了一个searchModel类:
class ObjectSearch extends Object
{
public function rules()
{
return [
[['type'], 'integer'],
[['name', 'city', 'countryId'], 'string']
];
}
//some other functions
public function search($params)
{
$query = Object::find()->where(['userId' => Yii::$app->user->id]);
$query->joinWith('country');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['countryId'] = [
'asc' => ['countries.name' => 'ASC'],
'desc' => ['countries.name' => 'DESC']
];
if (!$this->load($params) && $this->validate()) {
return $dataProvider;
}
$query->andFilterWhere(['like', 'objects.name', $this->name])
->andFilterWhere(['like', 'city', $this->city])
->andFilterWhere(['=', 'objects.countryId', $this->countryId])
->andFilterWhere(['=', 'type', $this->type]);
return $dataProvider;
}
}
排序和搜索工作正常 - 我得到了正确的结果。那我的问题是什么?对于标准列,当我在textInput中键入一些文本时,此输入的值在搜索后保留在其中。但是当我在Select2小部件搜索工作中选择一些值时,但在搜索之后所选的值消失了,我只有一个占位符。
感谢您的帮助,
卡米尔
答案 0 :(得分:3)
您应该只使用initValueText
param:
initValueText
:string,在Select2小部件中显示的初始值的文本。
e.g。 :
Select2::widget([
'name' => 'ObjectSearch[type]',
'data' => Object::typeNames(),
'initValueText' => $searchModel->type,
// ... other params
])
您也可以将它用作InputWidget:
Select2::widget([
'model' => $searchModel,
'attribute' => 'type',
'data' => Object::typeNames(),
// ... other params
])