Yii2:将列表框多选字段保存到db

时间:2015-01-19 18:46:27

标签: php listbox yii2

我在我的模型Appointment.php

中创建了一个列表框和相关函数

验证规则& Appointment.php中的相关功能

public function rules()
    {
        return [            
            ['weekdays', 'validateWeekDays'],

        ];
    }

public static function getWeekdaysList()
        {
            return [
                'monday' => 'Monday',
                'tuesday' => 'Tuesday',
                'wednesday' => 'Wednesday',
                'thursday' => 'Thursday',
                'friday' => 'Friday',
                'saturday' => 'Saturday',
                'sunday' => 'Sunday',
            ];
        }
    public function validateWeekdays ($attribute, $params)
        {
            $label = '«' . $this->getAttributeLabel($attribute) . '»';

            // Checking if it's array first
            if (is_array(!$this->$attribute)) {    
                $this->addError($attribute, "$label must be array.");

                return;
            }

            $allowedWeekdays = array_keys(static::getWeekdayslist());

            // Checking if every selection is in list of allowed values
            foreach ($this->$attribute as $weekday) 
            {
                if (!in_array($weekday, $allowedWeekdays)) {
                    $this->addError($attribute, "$label - $weekday is not in allowed list");
                }
            }

然后在我的_form.php

<?= $form->field($model, 'weekdays')->listBox(app\models\Appointment::getWeekdaysList(), [
    'multiple' => true,
    'size' => 7,
]) ?> 

现在在保存表单时,我收到的错误如下: 数据库异常 - yii \ db \ Exception

PDOStatement::bindValue() expects parameter 3 to be long, string given
Failed to prepare SQL: INSERT INTO `appointment` (`appointment_id`,
`appointment_date`, 
 `patient_detail_id`, `patient_name`, 
`priority`, `doctor_name`, `doctor_fee`, 
`discount`, `weekdays`, `total_amount`, 
`is_paid`, `hospital_commission`) VALUES 
(:qp0, :qp1, :qp2, :qp3, :qp4, :qp5, 
:qp6, :qp7, :qp8, :qp9, :qp10, :qp11)

我需要做些什么来纠正这个错误。感谢。

2 个答案:

答案 0 :(得分:2)

在将数组保存到数据库字段(应该是VARCHAR)之前尝试序列化数组:

public function beforeSave($insert)
{
    if (parent::beforeSave($insert)) 
    {
        $this->weekdays = serialize($this->weekdays);
        return true;
    }
}

然后在再次获取时进行反序列化:

public function afterFind()
{
    parent::afterFind();
    $this->weekdays = unserialize($this->weekdays);
}

确保在渲染表单时再次拥有一个数组。您可以对yii\helpers\Json::encode()yii\helpers\Json::decode()执行相同操作。

答案 1 :(得分:1)

好的我需要的只是一个功能而且效果很好。

public function beforeSave($insert)
        {       
        $weekday = implode(",", $this->weekdays);
        $this->weekdays = $weekday;
        return parent::beforeSave($insert);
        }

在控制器更新操作中,我添加了行

$model->weekdays = explode(',', $model->weekdays);

感谢。