S
S
Sergey2016-09-03 14:38:09
Yii
Sergey, 2016-09-03 14:38:09

Yii2, activerecord - how to record and validate a select miltiple field?

1. Actually in the controller:

$model = new Model;
$model->load(Yii::$app->request->post());
if($model->validate()) {
 $model->save();
}

2. In view
<select name=Model['select'] multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

Is there a standard way to write and validate an array via activerecord? Or do I need to write my own validator for this field? And how it is possible to write down in that case values ​​from an array as insert lines?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2016-09-04
@Gadz

Good evening.
Try like this.
In the model:

public $select_list;
    public function rules()
    {
        return [
              ['select_list', 'required'],
              ['select_list', 'each', 'rule' => ['integer']]
        ];
    }

    public static function getValuesArray()
    {
        return [
           'first' => 'first',
           '1' => 'second',
           '2' => 'third'
        ];
    }

In the form, in ActiveForm:
Select the second or third item - validation passes, if you select the first and second (third), then the validation does not pass, it requires an integer.
ps CheckText model name, change to your value

A
Andrew, 2016-09-04
@mhthnz

For these kinds of fields, the MySQL SET type is usually used, which allows you to select multiple values. There is a behavior that automatically converts to and from an array:
https://github.com/mhthnz/yii2-helpful-behaviors#y...
Regarding your code:

public function rules()
{
    return [
        ['select', 'required'],
        ['select', 'each', 'rule' => ['in', 'range' => ['volvo', 'saab', 'opel', 'audi']]],
    ];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question