Formatting values in Gridview using a custom class::function

Hi folks,

I am looking for some help on how to utilise this.

The problem is quite simple - I have a custom class I want to use to format $data->value fields. However, I am not sure as how to do this. It should also be pointed out that this project (moving an old project from Yii1 to Yii2) is really the first time I have used Yii2 and namespaces.

The custom class currently sits in: -

app\components\helpers\DateTimeHelper

The function I wish to use in the Gridview is DateTimeHelper::getDisplayDateTime()

Could I have some advice on how I would go about doing this? In the Yii2 version of the app, I used this same class and simply used include() to get use of the class but I am pretty stumped as to how to namespace and use the class/function.

Any advice GREATLY appreciated.

U4EA

Your custom class registered in "/app/components/helpers" should be like :




namespace app\components\helpers;


class DateTimeHelper

{

  public static function getDisplayDateTime($date)

  {

    ...

  }

}



And to use it in your view :




...

<?= GridView::widget([

    'dataProvider' => $dataProvider,

    'filterModel' => $searchModel,

    'columns' => [

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


      'id',

      ...

      [

        'attribute' => 'date'

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

          return app\components\helpers\DateTimeHelper::getDisplayDateTime($model->date);

        }

      ],

      ...

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

        ],

    ]); ?>

...



1 Like

That’s brilliant! Thank you very much!