B
B
Bogdan Pasechnik2014-09-09 11:22:41
Yii
Bogdan Pasechnik, 2014-09-09 11:22:41

What pitfalls can be in the implementation of working with array fields in the model?

I needed to work with some attributes as arrays.
For example, there is a list of checkboxes

<?= $form->field($model, 'parents')->checkboxList([1=>'значение 1', 2=>'значение 2', 3=>'значение 3']); ?>

In this case, an array is sent to the model as a post. And naturally we can only write a string to the database.
I have tried different solutions. Now this came to mind.
1. I create a validator that checks that the value is only an array and put it on the parents field
2. I override the base ActiveRecord model
...
    public function typeArrayAttributes()
    {
        return ['parents'];
    }

    public function __get($name)
    {
        $value = parent::__get($name);
        if(in_array($name, $this->typeArrayAttributes())) {
            $value = empty($value) ? [] : explode(',', $value);
        }
        return $value;
    }

    public function __set($name, $value)
    {
        if(is_array($value) && in_array($name, $this->typeArrayAttributes())) {
            $value = implode(',', $value);
        }
        parent::__set($name, $value);
    }
...

The typeArrayAttributes method defines a list of attributes whose values ​​are only arrays.
Now I get an array and not a string through $model->parents. And I can also assign only arrays $model->parents = ['value 1', 'value 2'];
At this stage, everything suits me. But since I modified the basic work of the model, there may be nuances that I did not take into account. About this and the question.
PS predicting possible questions, I inform you that I know what many_many connections are and actively use them. But in this case, I need to work with some fields as arrays.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Andreevich, 2014-09-09
@reffy

Why not do it within the framework of the validator and static methods of the model? Like in the example of creating a blog in Yii - yiiframework.ru/doc/blog/ru/post.model
Why do __set and __get at all? Why touch the underlying ActiveRecord model?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question