Gridview - reuse data from a column for another column




<?= GridView::widget([

        'dataProvider' => $dataProvider,

        'columns' => [

            [

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

                'options' => ['style' => 'width: 30px']

            ],

            [

                'label' => 'Budget',

                'format' => 'decimal', 

                'value' => function ($model){

                    return $model->getBudget();

                }

            ],

            [

                'label' => 'Actual',

                'format' => 'decimal',

                'value' => function ($model) {

                    return $model->getActual();

                }

            ],

            [

                'label' => 'Percent Complete',

                'format' => 'percent',

                'value' => function ($model) {

                    $actual = $model->getActual();

                    $budget = $model->getBudget();

                    return ($budgetQuantity > 0 ) ? $actualQuantity / $budgetQuantity : 0 ;

                }

            ]

        ]

    ]); ?>



As you can see, the Percent Complete colummn use the same data from Budget and Actual column. It is nice if I can re-use Budget and Actual data. Any idea ?

Calculate the values (‘budget’, ‘actual’, and ‘percent’) in the model and cache them.




private $_budget = null;

private $_actual = null;

private $_budget = null;


public function getBudget()

{

    if ($this->_budget === null) {

        ... calculate ...

        $this->budget = xxx;

    }

    return $this->_budget;

}


public function getActual()

{

    if ($this->_actual === null) {

        ... calculate ...

        $this->actual = xxx;

    }

    return $this->_actual;

}


public function getPercent()

{

    $budget = $this->getBudget();

    $actual = $this->getActual();

    if ($budget != 0) {

        return $actual / $budget;

    } else {

        return 0;

    }

}




I got it. Thanks