Search code examples
yii2

Yii2 DateControl: How to set default value (date)


I have in views/example/_form.php the following date field:

use yii\widgets\ActiveForm;
use kartik\datecontrol\DateControl;
...
$form = ActiveForm::begin();
...
echo $form->field($model, 'date')->widget(DateControl::className(), [
        'type' => DateControl::FORMAT_DATE,
        // 'value' => date('Y-m-d'),
        // 'value' => date('d.m.Y'),
        // 'value' => time(),
        // 'value' => '02.12.2015',
        // 'value' => '2015-12-02',
        // 'value' => '2015-12-02 00:00:00 0000',
        // 'value' => date('Y-M-d'),
        // 'value' => date('d.M.Y'),
        // 'value' => date('dd.MM.yyyy'),
]);
...
ActiveForm::end();

None of my attempts to set the default date was successfull (see the commented lines above). I have always received no error message and no default value. The resulting HTML input field looks always the same (the 'value' is empty):

<input type="text" id="yiiversion-date-disp" class="form-control" name="date-yiiversion-date" value="" data-krajee-datecontrol="datecontrol_1e107159" data-datepicker-source="yiiversion-                     date-disp-kvdate" data-datepicker-type="2" data-krajee-kvdatepicker="kvDatepicker_0aa71c62">

Configuration in config/main.php looks like this:

'modules' => [
    'datecontrol' =>  [
        'class' => 'kartik\datecontrol\Module',
        'autoWidget' => true,
        'autoWidgetSettings' => [
            'date' => [
                'pluginOptions' => [
                    'autoclose' => true,
                    'todayHighlight' => true,
                    'todayBtn' => true,
                ],
            ],
        ],
    ],
],

The dates are displayed as 01.01.2015 ('dd.MM.yyyy') and saved as 2015-01-01 ('Y-M-d') - MySQL datatype DATE.

More information:


Solution

  • As suggested by InsaneSkull the solution is quite simple. I had to add to the correspondig controller only: $model->date = date('Y-m-d');

    The resulting action could look e.g. like this:

    public function actionCreate()
    {
        $model = new YiiTask();
    
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $model->date = date('Y-m-d');
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }