Reputation: 3844
I have a table/model "seminar" (Trainings) and a table/model "category". They are connected through the field "seminar.category_id" so e.g. that I can use seminar->category->name. That all works.
Now I want to render a GridView-widget for each category, containing the corresponding seminars.
1) Should I use multiple GridViews or is there a better way (I need no filtering, etc.)
2) If answer of 1) is yes GridView, how should I implement it?
Sorry for the short question, if necessary I can post more details, but it's more a conceptual question.
UPDATE - solution:
The answer of Hesam pointed me in the right direction. Since I have to modified the answer I will post my solution here.
Note: I used ActiveDataProvider
SeminarController/actionIndex:
$categories = Category::find()->where(['Status'=>Category::STATUS_ACTIVE])->All();
$dataProviders = [];
foreach ($categories as $category) {
$dataProviders[] = new ActiveDataProvider([
'query' => $category->getSeminars(),
]);
}
return $this->render('index', compact('dataProviders'));
Struggled with getting the views to show - dont't work with:
<?php foreach(...){ $this->render()}... ?>
view/seminar/index.php:
<?php
foreach ($dataProviders as $dataProvider) {
?>
<?=
$this->render('_categoryRow', [
'dataProvider' => $dataProvider,
]);
?>
<?php } ?>
/view/seminar/_categoryRow.php:
<?= GridView::widget([
'dataProvider' => $dataProvider,
...
Additional tips:
Getting the current category name from $dataProvider ("name" is a column of "category")
$dataProvider->query->primaryModel->name
Getting the current count of seminars from $dataProvider
$dataProvider->getCount()
Upvotes: 0
Views: 3655
Reputation: 480
One approach is to use multiple data providers with multiple widgets. Consider we have this code in our action:
$categories = Category::find()->All();
$dataProviders = [];
foreach ($categories as $category) {
$dataProviders[] = new ArrayDataProvider([
'allModels' => $category->seminars,
'sort' =>['attributes' => ['id'],], // Here you can choose your custom attributes for sorting
'pagination' => ['pageSize' => 100]
]);
}
return $this->render('test', compact('dataProviders'));
By looping through $dataProviders
array in view, we can show all categories with their child seminars:
foreach ($dataProviders as $dataProvider) {
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'foo',
'bar',
'created_at:relativeTime',
'updated_at:relativeTime',
],
]) ;
}
Hope it can help.
Upvotes: 2