I am created a listbox and related functions like in my model Appointment.php
Validation Rule & related function in 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");
}
}
Then in my _form.php
<?= $form->field($model, 'weekdays')->listBox(app\models\Appointment::getWeekdaysList(), [
'multiple' => true,
'size' => 7,
]) ?>
Now while saving the form I am getting the error like: Database Exception – 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)
What I need to do to correct this error. Thanks.
Json::encode()to save the array as a json string, which is nice for complicated arrays.validateWeekdays, you can simply useinvalidator...