There was a need to write in the database table certain time and date (time and date in the table separate fields), through ActiveForm. I do not want to clutter up the project with 100,500 plugins, are there any other options, regular Yii?

  • Well look. You can just make an assignment after calling the model. $ model = new Model () $ model-> date = '2018-03-13' $ model-> time = '13: 00: 00 '$ model-> save () - Anatoliy.CHA
  • Already closer. BUT, I want through ActiveForm-> field. Why here after this construction <? = $ Form-> field ($ model, 'date') -> input ('text'); ?> the correct date is not recorded in the database, but zeros are written of the type: 0000-00-00. In the Input field, I enter the date in such a format 2018-09-12 for example. - pbdev
  • ps: Well, you understand, in the database table there is a date field - pbdev

2 answers 2

Goodnight. To write the date in the database there is a behavior yii \ behaviors \ TimestampBehavior Used as follows

use yii\behaviors\TimestampBehavior; public function behaviors() { return [ TimestampBehavior::class, ]; } 

Details here

There is also a built-in yii \ jui \ DatePicker.

The rest depends on what you need in the end.

  • TimestampBehavior automatically fills the time with the current timestamp. I do not need the current time and dates, but any, say 2018-06-12 - pbdev
  • And the DatePicker is something I haven't built in - pbdev
  • So in the latest versions excluded. Separately need to put. yiiframework.com/doc-2.0/yii-jui-datepicker.html - user216615
  • github.com/yiisoft/yii2-jui - user216615 10:39 pm

In general, I found a solution, and as always, everything is trivially simple. I added the following code in the model rules:

 public function rules() { return [ [['title', 'content', 'date', 'time'], 'required'], **['date', 'date', 'format' => 'php:Ym-d'], // для даты** **['time', 'time', 'format' => 'php:H:m:s'], // и для времени** [['author_id'], 'integer'], ['title', 'string', 'length' => [5,25] ], [['content'], 'string', 'length' => [5,255] ] ]; } 

In total, everything comes from the form as it should, the date and time in the database are recorded correctly and nothing needs to be done in the controller-> actionCreate. Here is the form itself:

 <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'title')->textInput(['maxlength' => 25]) ?> <?= $form->field($model, 'content')->textarea(['rows' => 6]) ?> <?= $form->field($model, 'date')->input('text'); ?> <?= $form->field($model, 'time')->input('text'); ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? Yii::t('backend', 'Create') : Yii::t('backend', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> 

And in the controller is standard:

 public function actionCreate() { $model = new Event(); if ($model->load(Yii::$app->request->post()) && $model->save()) { ..... }