Date Formatting In Forms

Hello and my greetings and congrats to Yii team for such a nice framework.

I am new to Yii and to this forum.

I have just installed advanced application template for yii2.

Now I am faced with couple of issues at the very start.

1.When creating CRUD for Model in Gii it is now asking too many questions. Need to understand or a guideline for choosing namespace correctly or any undesirable affect in not following the norms.

  1. When trying to use the date picker widget in the active form I have inserted this code

<?= $form->field($model,'admission_date')->widget(DatePicker::className(),['clientOptions' => ['dateFormat' => 'yy-mm-dd']]) ?>

I get the error that DatePicker class couldn’t be found. Then I replace code like:


<?= $form->field($model,'admission_date')->widget(yii\jui\DatePicker::className(),['clientOptions' => ['dateFormat' => 'yy-mm-dd']]) ?>

It start showing the DatePicker widget.

So the question is am I right in adding path information to DatePicker or I have not configured the Yii correctly?

  1. Again I wanted to change the Date format to ‘dd-mm-yy’ and edited the code accordingly. The input start showing the correct format, but on save, the result was ‘0000-00-00’. If I keep the format as it is, the dates are getting saved correctly.

Here what I am doing wrong.

So many questions for the first post.

Thanks.

Yes the second approach is correct… you need to use namespaces for classes in Yii 2.0.

An alternative approach (in case you want to just use the class name and probably more than one place in your code):




use yii\jui\DatePicker;

<?= $form->field($model,'admission_date')->widget(DatePicker::className(),['clientOptions' => ['dateFormat' => 'yy-mm-dd']]) ?>



Thanks so much.

But How about the date formatting? I am not able to save the dates with date formatted as ‘dd-mm-yy’ as also how to create namespaces while generating models and CRUD?

For the second part of your query: you may want to read about namespaces in PHP. If you check any class in Yii you have at the top – the namespace for the class… for example your model class:




namespace frontend\models;

use yii\base\Model;

class YourModel extends Model {

   // your code

}



For the first part of your query: depends on how your database field is set (e.g. is it INT or TIMESTAMP or DATETIME for MySQL). You could handle that transformation in your model beforeSave() or the controller action before calling $model->save() - something like this in your model:




public function beforeSave($insert) {

    // unix timestamp

    $time = strtotime($model->admission_date);


    // if you want a specific format

    $time = date("Y-m-d", strtotime($model->admission_date));


    // any other custom validations you need for your date time

    // e.g. isTheTimeOk($time);

    if (isTheTimeOk($time)) {

        $model->admission_date = $time;

        return parent::beforeSave($insert);

    }

    else {

        return false;

    }

}



Thank you so much.

Can you please tell me how the same code is not working in index.php gridview

The code I am using looks like this:




<?php echo GridView::widget([

		'dataProvider' => $dataProvider,

		'filterModel' => $searchModel,

		'columns' => [

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

....

....

array(

        'label'=>'Admission Date',

        'value'=>date("d-m-Y",strtotime($this->admission_date)),

                         ),

...

...



I have also viewed this post(http://www.yiiframework.com/forum/index.php/topic/19166-displaying-date/page__view__findpost__p__93898), which confirms that the above code should work.

The error I am getting is like this:

Unknown Property – yii\base\UnknownPropertyException

Getting unknown property: yii\web\View::admission_date

Each datacolumn’s value in gridview needs to be specified as a Closure. Check the gridview and Data Column code documentation. e.g.




'columns' => [

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

    ...

    [

        'label' => 'Admission Date',

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

            return date("d-m-Y", strtotime($model->admission_date);

        }

    ]

]



A Big thank you. Works perfectly.

a small problem though. Sorting and filter for that field is gone.

Yes… you still need to pass the source attribute field for filtering/sorting:




'columns' => [

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

    ...

    [

        'attribute' => 'admission_date',

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

            return date("d-m-Y", strtotime($model->admission_date);

        }

    ]

]



BUT… a better method… in your case, since you require to just format the date (if you are already saving the date as unix timestamp)… simply you can use this:




'columns' => [

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

    ...

    [

        'attribute' => 'admission_date',

        'format' => ['date', 'd-M-Y'],

    ]

]



Thanks once Again.

That is much better.

Hi, i have same problem when trying to format date before update/insert record.

I change date display in view and i have to change it again for DB.

I did this: LINK

on controller but i dont see any change, do i have to call this function?