Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 ListView and dataprovider

Tags:

php

listview

yii2

What data must be sended to dataprovider?

In my controller:

public function actionIndex() {
    $searchModel  = new UserSearch();
    $dataProvider = $searchModel->search( Yii::$app->request->queryParams );
//other stuff and sending array of params to view

in a view:

echo ListView::widget( [
    'dataProvider' => $dataProvider,
] );

but i got only id`s:

enter image description here

And if i`m set single view like:

'itemView' => '_single',

how send data to _single.php ?

I mean - need default template for view list items like in GridView:

GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'username',
        'email:email',
        'password',
        'role',
//....

And then i got perfect grid:

enter image description here

like image 564
WebArtisan Avatar asked Oct 15 '14 12:10

WebArtisan


2 Answers

Controller - SiteController.php

<?php

// Yii2 Listview Example : by Songwut Kanchanakosai, Thailand.

use common\models\Members;
use common\models\SearchMembers;
...

public function actionIndex() {
    $searchModel = new SearchMembers();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
?>

View (1) - index.php

<?php
use yii\widgets\ListView;
...
echo ListView::widget( [
    'dataProvider' => $dataProvider,
    'itemView' => '_item',
] ); ?>

View (2) - _item.php

<?php
use yii\helpers\Html;
?>  

<?=$model->name;?> 
<?=$model->age;?> 
<?=$model->mobile;?>

Example Result :

Songwut 36 +668-3949-5153
Prawee  41 +668-7323-2334
Kosol   32 +668-8014-0165
Utehn   39 +668-7874-5643
like image 73
Songwut K. Avatar answered Oct 16 '22 20:10

Songwut K.


how send data to _single.php ? Here is how, use $viewParams

$viewParams public property array $viewParams = []

Additional parameters to be passed to $itemView when it is being rendered. This property is used only when $itemView is a string representing a view name.

echo ListView::widget( [
    'dataProvider' => $dataProvider,
    'viewParams'=>['name'=>'My Name is Stefano'], //acccessed in view as $name with value 'My Name is Stefano'
] );
like image 3
Stefano Mtangoo Avatar answered Oct 16 '22 21:10

Stefano Mtangoo