Hello.

There is, for example, a User model. In the database, there is a user table and there is a data field (it includes the date and time. The record has the form 01.01.2018 13:00:00).

I created the start_data and start_time fields in the user model.

How it will be correct to make a method which will pull out date and will break it into two fields start_date and start_time? This is necessary in order to be able to edit the start date separately through the form, separately the start time.

I imagine that it will look like this in a model.

public function createStartDate(){ $arrDateAndTime = explode(" ",$this->date); $start_date = $arrDateAndTime[0]; return ['start_date' => $start_date]; } public function createStartTime(){ $arrDateAndTime = explode(" ",$this->date); $full_start_time = explode(':',$arrDateAndTime[1]); $start_time = $full_start_time[0] . ":" . $full_start_time[1]; return ['start_time' => $start_time]; } 

How will it be necessary to return the correct fields so that they are displayed in the form?

In the controller, I simply call the desired model by id:

 public function actionIndex() { $user = User::findOne(540); return $this->renderAjax('userchange',['user' => $user]); } 

Fields in the view has the form:

 echo $form->field($user, 'start_date'); echo $form->field($user, 'start_time'); 
  • one
    $ time = date ('H: m: i', strtotime ($ user-> data)); $ date = date ('dmY', strtotime ($ user-> data)); // And no parsing of lines - Daniel Protopopov
  • @DanielProtopopov Hmm. You will consider this option. But I already want to know how it will be right to return the fields to the model. - Anatoliy.CHA

1 answer 1

In the comments you were offered the best option for forming the date.

Yii itself loads the necessary data into the ActiveForm fields, if they correspond to the model fields, we can create some artificially, below showed how this can be done

Create User Model Methods

 public function afterFind() { $date = merge_array($this->createStartDate(), $this->createStartTime()); $this->date = $date; // послС Π²Ρ‹Π³Ρ€ΡƒΠ·ΠΊΠΈ ΠΈΠ· Π±Π°Π·Ρ‹ Π΄Π΅Π»Π°Π΅ΠΌ ΠΈΠ· строки массив с ΠΏΠΎΠΌΠΎΡ‰ΡŒΡŽ Π’Π°ΡˆΠΈΡ… ΠΌΠ΅Ρ‚ΠΎΠ΄ΠΎΠ² } public function beforeSave($insert) { if (parent::beforeSave($insert)) { $this->date = implode(' ', $this->date); // ΠΈΠ· массива Π΄Π΅Π»Π°Π΅ΠΌ строку ΠΏΠ΅Ρ€Π΅Π΄ Π·Π°Π³Ρ€ΡƒΠ·ΠΊΠΎΠΉ Π² Π±Π°Π·Ρƒ return true; } return false; } 

Further, the views in the view must have other names.

 echo $form->field($user, 'date[start_date]'); echo $form->field($user, 'date[start_time]'); 

You also need to remember to check and correct the rules.

PS In this case, you can close your createStartTime and createStartDate methods - make them private.

  • I understood the point, thanks for the answer. Went to apply. - Anatoliy.CHA