V
V
Vladimir2017-01-10 21:17:14
Yii
Vladimir, 2017-01-10 21:17:14

How to work with SET field in Yii2?

Good day!
Please tell me, I have a field in the database with the SET type. How can I pass values ​​to it using ActiveForm.
Tried like this:

<?= $form->field($model, 'communication')->checkboxList(['Свет' => 'Свет', 'Газ' => 'Газ', 'Вода' => 'Вода']) ?>

So nothing works. Gives an error message. Please tell me how to implement it. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2017-01-11
@MasterGerold

Currently, Yii2 does not fully support the MySQL SET type. But you can implement the logic of working with this type yourself by adding to your ActiveRecord class, for example:

/**
 * Ваш класс ActiveRecord описывающий таблицу содержащую поле с типом SET
 *
 * @property string $communication Название поля в таблице хранящее SET-значения
 * @property string[] $communicationArr Атрибут который будет обрабатывать все значения в виде массива
 */
class MyAR extends \yii\db\ActiveRecord
{

    /**
     * Формирование правил валидации атрибутов
     */
    public function rules()
    {
        return [
            // Ваши правила валидации атрибутов
            [
                // правило валидации для поля типа SET
                'communication',
                'string'
            ]
        ];
    }

    /**
     * Формирование списка безопастных атрибутов
     */
    public function scenarios()
    {
        return [
            $this::SCENARIO_DEFAULT => [
                // Список атрибутов которые можно загружать через метод load
                'communicationArr'
            ] // атрибут с которым будем работать как с массивом

        ];
    }

    /**
     * Геттер свойства сommunicationArr
     */
    public function getCommunicationArr()
    {
        return explode(',', $this->communication);
    }

    /**
     * Cеттер свойства сommunicationArr
     */
    public function setCommunicationArr($value)
    {
        $this->communication = is_array($value) ? implode(',', $value) : '';
    }
}

and then just work with the communicationArr attribute ...

D
Dmitry, 2017-01-10
@slo_nik

Good evening.
Convert everything to numbers, not strings.
1 = 'Light',
2 = 'Gas'
3 = 'Water'
and so on .
Accordingly, in the database, change the field type to integer
. In the model, create a static method that returns an array

public static function getAllData()
{
   return [
       1 => 'Свет',
       2 => 'Газ',
      3 => 'Вода'
  ];
}

In checkboxList just call this method
<?= $form->field($model, 'communication[]')->checkboxList(Model::getAllData()) ?>
Note the square brackets around communication

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question