Yii2。型号:: loadMultipe。如何加载类字段?

时间:2016-11-28 15:38:58

标签: php yii2 yii2-basic-app yii2-model

如何不仅加载数据库属性,还加载// method InsertUser(List<User> data) comm.CommandText = "INSERT INTO TAccount (Username, Password, RolesID) VALUES (@UserId, @UserId, 4) " + "INSERT INTO TUser (UserId, Name, Birthday, Address) VALUES (@UserId, @Name, @Birthday, @Address)"; // HOW TO GENERATE VALUE DATA TO QUERY? comm.CommandType = CommandType.Text; conn.Open(); comm.ExecuteNonQuery(); 字段?

我有这样的模特

loadMultipe

这样的观点

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();
    }
}

在控制器中

<?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(); ?>

填充属性,但字段仍为空。我需要它们,因为我使用它来连接并在数据库中创建一个日期字段。如何加载它们?

3 个答案:

答案 0 :(得分:0)

您可以使用datepicker小部件来设置包含日,月和年的日期生日,此小部件是日历

答案 1 :(得分:0)

试试这个

$formDetails = Yii::$app->request->post('Person', []);
foreach ($formDetails as $i => $value) 
{
  $model = new Person();
  $model->setAttributes($value);
  $models[] = $model;
}

答案 2 :(得分:0)

应该在视图中添加迭代器到传递数组

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