Yii 2.0 Kartik gridview Expand Row Column Widget issue with related data

Hi,

I’m a yii newbie and I cannot display related data through Expand Row Column Widget: I get an Undefined variable: dataProvider error.

Controller:


 <?php


    namespace app\controllers;


    use Yii;

    use app\models\Incarico;

    use app\models\IncaricoSearch;

    use yii\web\Controller;

    use yii\web\NotFoundHttpException;

    use yii\filters\VerbFilter;

    use yii\helpers\Json;





    /**

     * IncaricoController implements the CRUD actions for Incarico model.

     */

    class IncaricoController extends Controller

    {

        [...]


        public function actionIndex()

     	{

            // your default model and dataProvider generated by gii

    	    $searchModel = new IncaricoSearch;

    	    $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());

    	    $dataProvider->pagination=['pagesize'=>5];


    	    // validate if there is a editable input saved via AJAX

    	    if (Yii::$app->request->post('hasEditable')) {

    	        // instantiate your incarico model for saving

    	        $id = Yii::$app->request->post('editableKey');

    	        $model = Incarico::findOne($id);


    	        // store a default json response as desired by editable

    	        $out = Json::encode(['output'=>'', 'message'=>'']);


    	        // fetch the first entry in posted data (there should 

    	        // only be one entry anyway in this array for an 

    	        // editable submission)

    	        // - $posted is the posted data for Incarico without any indexes

    	        // - $post is the converted array for single model validation

    	        $post = [];

    	        $posted = current($_POST['Incarico']);

    	        $post['Incarico'] = $posted;


    	        // load model like any single model validation

    	        if ($model->load($post)) {

    	            // can save model or do something before saving model

    	            $model->save();


    	            // custom output to return to be displayed as the editable grid cell

    	            // data. Normally this is empty - whereby whatever value is edited by 

    	            // in the input by user is updated automatically.

    	            $output = '';


    	            // similarly you can check if the name attribute was posted as well

    	            // if (isset($posted['name'])) {

    	            //   $output =  ''; // process as you need

    	            // } 

    			

    	            $out = Json::encode(['output'=>$output, 'message'=>'']);

    	        } 

    	        // return ajax json encoded response and exit

    	        echo $out;

    	        return;

    	    }


    	    // non-ajax - render the grid by default

    	    return $this->render('index', [

    	        'dataProvider' => $dataProvider,

    	        'searchModel' => $searchModel

    	    ]);

    	}


        [...]


        protected function findModel($id)

        {

            if (($model = Incarico::findOne($id)) !== null) {

                $model = Incarico::find()

                ->select([

                    'incarico.*',

                    'allegato.idIncarico',

                    'allegato.nomeFile',

                ])

                ->innerJoinWith('allegatos')

                ->one();


                return $model;




            } else {

                throw new NotFoundHttpException('The requested page does not exist.');

            }

        }

    }



Model:




    <?php


    namespace app\models;


    use Yii;


    /**

     * This is the model class for table "incarico".

     *

     * @property integer $id

     * @property integer $protocollo

     * @property integer $idAssicurato

     * @property integer $idFiliale

     * @property integer $idCompagnia

     * @property integer $numeroPolizza

     * @property integer $idTipoPolizza

     * @property string $dataSinistro

     * @property integer $idTipoEvento

     * @property string $indirizzoSinistro

     * @property string $localitaSinistro

     * @property integer $capSinistro

     * @property string $provinciaSinistro

     * @property integer $idSopralluogo

     * @property string $dataIncarico

     * @property integer $idStatoIncarico

     * @property integer $idStatoPerizia

     * @property integer $idIncaricato

     * @property integer $idResponsabile

     * @property string $dataScadenza

     * @property string $broker

     * @property integer $amministratore

     * @property integer $idLiquidatore

     *

     * @property Allegato[] $allegatos

     * @property Assicurato $idAssicurato0

     * @property Compagnia $idCompagnia0

     * @property Filiale $idFiliale0

     */

    class Incarico extends \yii\db\ActiveRecord

    {

        /**

         * @inheritdoc

         */

        public static function tableName()

        {

            return 'incarico';

        }


        /**

         * @inheritdoc

         */

        public function rules()

        {

            return [

                [['protocollo', 'idAssicurato', 'idFiliale', 'idCompagnia', 'numeroPolizza', 'idTipoPolizza', 'idTipoEvento', 'capSinistro', 'idSopralluogo', 'idStatoIncarico', 'idStatoPerizia', 'idIncaricato', 'idResponsabile', 'amministratore', 'idLiquidatore'], 'integer'],

                [['dataSinistro', 'dataIncarico', 'dataScadenza'], 'safe'],

                [['indirizzoSinistro', 'localitaSinistro', 'provinciaSinistro'], 'string', 'max' => 11],

                [['broker'], 'string', 'max' => 255]

            ];

        }


        /**

         * @inheritdoc

         */

        public function attributeLabels()

        {

            return [

                'id' => 'ID',

                'protocollo' => 'Protocollo',

                'idAssicurato' => 'Id Assicurato',

                'idFiliale' => 'Id Filiale',

                'idCompagnia' => 'Id Compagnia',

                'numeroPolizza' => 'Numero Polizza',

                'idTipoPolizza' => 'Id Tipo Polizza',

                'dataSinistro' => 'Data Sinistro',

                'idTipoEvento' => 'Id Tipo Evento',

                'indirizzoSinistro' => 'Indirizzo Sinistro',

                'localitaSinistro' => 'Localita Sinistro',

                'capSinistro' => 'Cap Sinistro',

                'provinciaSinistro' => 'Provincia Sinistro',

                'idSopralluogo' => 'Id Sopralluogo',

                'dataIncarico' => 'Data Incarico',

                'idStatoIncarico' => 'Id Stato Incarico',

                'idStatoPerizia' => 'Id Stato Perizia',

                'idIncaricato' => 'Id Incaricato',

                'idResponsabile' => 'Id Responsabile',

                'dataScadenza' => 'Data Scadenza',

                'broker' => 'Broker',

                'amministratore' => 'Amministratore',

                'idLiquidatore' => 'Id Liquidatore',

            ];

        }


        /**

         * @return \yii\db\ActiveQuery

         */

        public function getAllegatos()

        {

            return $this->hasMany(Allegato::className(), ['idIncarico' => 'id']);

        }


        /**

         * @return \yii\db\ActiveQuery

         */

        public function getIdAssicurato0()

        {

            return $this->hasOne(Assicurato::className(), ['id' => 'idAssicurato']);

        }


        /**

         * @return \yii\db\ActiveQuery

         */

        public function getIdCompagnia0()

        {

            return $this->hasOne(Compagnia::className(), ['id' => 'idCompagnia']);

        }


        /**

         * @return \yii\db\ActiveQuery

         */

        public function getIdFiliale0()

        {

            return $this->hasOne(Filiale::className(), ['id' => 'idFiliale']);

        }

    }



ModelSearch:




    <?php


    namespace app\models;


    use Yii;

    use yii\base\Model;

    use yii\data\ActiveDataProvider;

    use app\models\Incarico;


    /**

     * IncaricoSearch represents the model behind the search form about `app\models\Incarico`.

     */

    class IncaricoSearch extends Incarico

    {

        /**

         * @inheritdoc

         */

        public function rules()

        {

            return [

                [['id', 'protocollo', 'idAssicurato', 'idFiliale', 'idCompagnia', 'numeroPolizza', 'idTipoPolizza', 'idTipoEvento', 'capSinistro', 'idSopralluogo', 'idStatoIncarico', 'idStatoPerizia', 'idIncaricato', 'idResponsabile', 'amministratore', 'idLiquidatore'], 'integer'],

                [['dataSinistro', 'indirizzoSinistro', 'localitaSinistro', 'provinciaSinistro', 'dataIncarico', 'dataScadenza', 'broker'], 'safe'],

            ];

        }


        /**

         * @inheritdoc

         */

        public function scenarios()

        {

            // bypass scenarios() implementation in the parent class

            return Model::scenarios();

        }


        /**

         * Creates data provider instance with search query applied

         *

         * @param array $params

         *

         * @return ActiveDataProvider

         */

        public function search($params)

        {

           // $query = Incarico::find();

            $query = Incarico::find();


            $dataProvider = new ActiveDataProvider([

                'query' => $query,

            ]);


            $this->load($params);


            if (!$this->validate()) {

                // uncomment the following line if you do not want to any records when validation fails

                // $query->where('0=1');

                return $dataProvider;

            }


            $query->andFilterWhere([

                'id' => $this->id,

                'protocollo' => $this->protocollo,

                'idAssicurato' => $this->idAssicurato,

                'idFiliale' => $this->idFiliale,

                'idCompagnia' => $this->idCompagnia,

                'numeroPolizza' => $this->numeroPolizza,

                'idTipoPolizza' => $this->idTipoPolizza,

                'dataSinistro' => $this->dataSinistro,

                'idTipoEvento' => $this->idTipoEvento,

                'capSinistro' => $this->capSinistro,

                'idSopralluogo' => $this->idSopralluogo,

                'dataIncarico' => $this->dataIncarico,

                'idStatoIncarico' => $this->idStatoIncarico,

                'idStatoPerizia' => $this->idStatoPerizia,

                'idIncaricato' => $this->idIncaricato,

                'idResponsabile' => $this->idResponsabile,

                'dataScadenza' => $this->dataScadenza,

                'amministratore' => $this->amministratore,

                'idLiquidatore' => $this->idLiquidatore,


            ]);


            $query->andFilterWhere(['like', 'indirizzoSinistro', $this->indirizzoSinistro])

                ->andFilterWhere(['like', 'localitaSinistro', $this->localitaSinistro])

                ->andFilterWhere(['like', 'provinciaSinistro', $this->provinciaSinistro])

                ->andFilterWhere(['like', 'broker', $this->broker]);


            return $dataProvider;

        }

    }



index View:





	<?php


	use yii\helpers\Html;

	use yii\helpers\Url;

	use kartik\grid\GridView;

	use kartik\editable\Editable;

	use yii\helpers\ArrayHelper;

	use app\models\Assicurato;

	use app\models\Incarico;




	/* @var $this yii\web\View */

	/* @var $searchModel app\models\IncaricoSearch */

	/* @var $dataProvider yii\data\ActiveDataProvider */


	$this->title = 'Incaricos';

	$this->params['breadcrumbs'][] = $this->title;





	?>


	<div class="incarico-index">


		<h1><?= Html::encode($this->title) ?></h1>

		<?php //echo $this->render('_search', ['model' => $searchModel]); ?>

		<?php


		$gridColumns = [

			[

	        	'class' => '\kartik\grid\SerialColumn'

			],		

			

            [...]


			[

				'class' => 'kartik\grid\ExpandRowColumn',

				'expandAllTitle' => 'Expand all',

				'collapseTitle' => 'Collapse all',

				'expandIcon'=>'<span class="glyphicon glyphicon-expand"></span>',

				'value' => function ($model, $key, $index, $column) {

					return GridView::ROW_COLLAPSED;

				},

				'detail'=>function ($model, $key, $index, $column) {

					return Yii::$app->controller->renderPartial('_allegato-expand.php', ['model'=>$model]);

				},

				

	            'detailOptions'=>[

	                'class'=> 'kv-state-enable',

	            ],

			],

		



_allegato-expand view:




    <?php


    use yii\helpers\Html;

    use yii\grid\GridView;

    use yii\widgets\DetailView;


    /* @var $this yii\web\View */

    /* @var $searchModel app\models\AllegatoSearch */

    /* @var $dataProvider yii\data\ActiveDataProvider */


    $this->title = 'Allegatos';

    $this->params['breadcrumbs'][] = $this->title;

    ?>

    <div class="allegato-index">


        <h1><?= Html::encode($this->title) ?></h1>

        <?php // echo $this->render('_search', ['model' => $searchModel]); ?>


        <p>

            <?= Html::a('Create Allegato', ['create'], ['class' => 'btn btn-success']) ?>

        </p>


        <?


        echo GridView::widget([

            'dataProvider' => $dataProvider,

            'filterModel' => $searchModel,

            'columns' => [

                ['class' => 'yii\grid\SerialColumn'],


                'id',

                'idIncarico',

                'nomeFile',


                ['class' => 'yii\grid\ActionColumn'],

            ],

        ]);

        

         ?>


    </div>



@view - ExpandRowColumn


 [

                                'class' => 'kartik\grid\ExpandRowColumn',

                                'expandAllTitle' => 'Expand all',

                                'collapseTitle' => 'Collapse all',

                                'expandIcon'=>'<span class="glyphicon glyphicon-expand"></span>',

                                'value' => function ($model, $key, $index, $column) {

                                        return GridView::ROW_COLLAPSED;

                                },

                                'detail'=>function ($model, $key, $index, $column) {

                                        return Yii::$app->controller->renderPartial('_allegato-expand.php', ['model'=>$model]);

                                },

                                

                    'detailOptions'=>[

                        'class'=> 'kv-state-enable',

                    ],},

u need to define dataprovider and searchmodel as ur render grid has assign that field.

But… aren’t dataprovider and searchmodel already defined in controller?




[...]

    return $this->render('index', [

        'dataProvider' => $dataProvider,

        'searchModel' => $searchModel

    ]);

[...]



I have used below code nd it works.


return Yii::$app->controller->renderPartial("/reply/index",[ 'searchModel' => $searchModel,'dataProvider' => $dataProvider]);

Hi and thank you for assistance :D … I tried:




'detail'=>function ($model, $key, $index, $column) {

    return Yii::$app->controller->renderPartial('_allegato-expand.php', ['searchModelAllegato' => $searchModelAllegato,'dataProviderAllegato' => $dataProviderAllegato]);

},

But gives me "Undefined variable: dataProviderAllegato"

Alex

Please is there someone with a little bit of patience that could explain me what I’m doing wrong?

I’ve already read docs about models, dataproviders, activequery bit I think I’m still stucked on basic concepts…

:( :(

_allegato-expand view:

&lt;?php





use yii&#092;helpers&#092;Html;


use yii&#092;grid&#092;GridView;


use yii&#092;widgets&#092;DetailView;





/* @var &#036;this yii&#092;web&#092;View */


/* @var &#036;searchModel app&#092;models&#092;AllegatoSearch */


/* @var &#036;dataProvider yii&#092;data&#092;ActiveDataProvider */





&#036;this-&gt;title = 'Allegatos';


&#036;this-&gt;params['breadcrumbs'][] = &#036;this-&gt;title;


?&gt;


&lt;div class=&quot;allegato-index&quot;&gt;





    &lt;h1&gt;&lt;?= Html::encode(&#036;this-&gt;title) ?&gt;&lt;/h1&gt;


    &lt;?php // echo &#036;this-&gt;render('_search', ['model' =&gt; &#036;searchModel]); ?&gt;





    &lt;p&gt;


        &lt;?= Html::a('Create Allegato', ['create'], ['class' =&gt; 'btn btn-success']) ?&gt;


    &lt;/p&gt;





    &lt;?





    echo GridView::widget([


        'dataProvider' =&gt; &#036;[color=&quot;#FF0000&quot;]dataProvider[/color],&#036;dataProviderAllegato


        'filterModel' =&gt; &#036;[color=&quot;#FF0000&quot;]searchModel[/color], &#036;searchModelAllegato


        'columns' =&gt; [


            ['class' =&gt; 'yii&#092;grid&#092;SerialColumn'],





            'id',


            'idIncarico',


            'nomeFile',





            ['class' =&gt; 'yii&#092;grid&#092;ActionColumn'],


        ],


    ]);


    


     ?&gt;





&lt;/div&gt;

‘detail’=>function ($model, $key, $index, $column) {

return Yii::&#036;app-&gt;controller-&gt;renderPartial('_allegato-expand.php', ['searchModelAllegato' =&gt; &#036;searchModelAllegato,'dataProviderAllegato' =&gt; &#036;dataProviderAllegato]);

},