Answer the question
In order to leave comments, you need to log in
Is there a good doc for GridView Yii2?
Good afternoon.
Understanding gridview. I would like to learn more (and more understandably) about the search in related tables. It doesn't work at all... :/
Advise the doc or good examples of how to set up filters considering relays.
Thanks in advance.
Answer the question
In order to leave comments, you need to log in
It's just that you create a search method in the model that should return \yii\data\ActiveDataProvider
The model can be the one associated with the base or it can be a form model.
Do we need only attributes and validation from the model for the grid? search method, since we use the filled attributes in the + GridView method above the Header column displays an input
/**
* @param $params
* @param $group
* @return \yii\data\ActiveDataProvider
*/
public function search($params, $group = null )
{
$this->scenario = self::SCENARIO_SEARCH; // когда у вас много правил по умолчанию следует использовать сценарии
// базовый поиск
$query = self::find();
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => $query,
]);
// Тут и нужный кастомные сценарии если базовая валидация мешает.
if (!( $this->load($params) && $this->validate())) {
return $dataProvider;
}
// применяем сортировку
$dataProvider->setSort([
'attributes' => [
'id',
]
]);
// добавляем к поиску условие например найти по диапазону даты.
if(!empty($this->dateFrom) && !empty($this->dateTo)) {
$query->andWhere('`hour_at` BETWEEN :dateFrom AND :dateTo', [
':dateFrom' => date('Y-m-d H:00:00', strtotime(trim($this->dateFrom))),
':dateTo' => date('Y-m-d H:59:59', strtotime(trim($this->dateTo))),
]);
}
// Добавляет условия если атрибуты нашей модели заполнены !=null
$query->andFilterWhere([
'stream_id' => $this->stream_id,
'country_id' => $this->country_id,
'browser' => $this->browser,
'os' => $this->os,
]);
return $dataProvider;
}
<?=GridView::widget([
'dataProvider' => $user->search(Yii::$app->request->get()),
'filterModel' => $user,
'columns' => [
'id',
'username' => [
'attribute' => 'username',
],
'email',
]]);?>
$query->join('left',Country::tableName(),'user.country_id='.Country::tableName().'.id');
$query->andFilterWhere([
Country::tableName().'.name' => $this->countryName
]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question