Search code examples
phpyii2yii2-basic-appyii2-model

Yii2. Model::loadMultipe. How to load class fields too?


How to load not only DB attributes, but fields too with loadMultipe?

I have such a model

class Person extends ActiveRecord
{

    public $birthdate_month;

    public $birthdate_day;

    public $birthdate_year;

...

    public function rules()
    {
        return [
            ...
            [['birthdate_month', 'birthdate_day', 'birthdate_year'], 'integer'],
            [['birthdate_month', 'birthdate_day', 'birthdate_year'], 'required']
        ];
    }

// I store data as one DATA field in DB and than use such methods to show it to the user

    public function afterFind()
    {
        if (isset($this->birthdate)) {
            $date = Carbon::createFromFormat('Y-m-d', $this->birthdate); //just a data-manipulation library

            $this->birthdate_month = $date->month;
            $this->birthdate_day   = $date->day;
            $this->birthdate_year  = $date->year;
        }

        return parent::afterFind();
    }



    public function beforeValidate()
    {
        $date            = Carbon::create($this->birthdate_year, $this->birthdate_month, $this->birthdate_day); //just a data-manipulation library
        $this->birthdate = $date->toDateString();

        return parent::beforeValidate();
    }
}

And such a view

<?php $form = ActiveForm::begin() ?>

<?php foreach ($children as $i => $child): ?> //there are multiple persons (children)

...

 <?=$form->field($child, '[]birthdate_month', [...])->dropDownList([
                    '1'  => 'January',
                    ...
                ])?>

...

<?php endforeach; ?>

...

<?=Html::submitButton('Save', ['class' => 'ui primary button big'])?>
...

<?php ActiveForm::end(); ?>

In controller

Person::loadMultiple($children, Yii::$app->request->post());

fills attributes, but fields are still null. I need them, cause I use it to concat and make one date field in the DB. How to load them too?


Solution

  • Should be added iterator to passing array in the view

     <?=$form->field($child, "[$i]birthdate_month", [...])->dropDownList([
                        '1'  => 'January',
                        ...
                    ])?>