mrateb
mrateb

Reputation: 2509

Yii2 - loadMultiple with form model

I have a very simple scenario where I'm receiving a list of Variance Positions from the end user. To be able to validate the structure of the input, I created the following model for the single item that I should receive:

class VariancePositionsForm extends Model{
    public $id;
    public $position;

    public function rules()
    {
        return [
            [['id','position'], 'required'],
            [['id', 'position'], 'integer'],
        ];
    }
}

And in the controller, I have the following:

    $variancePositions = [];
    for($i=0;$i<sizeof(Yii::$app->request->post());$i++)
    {
        $variancePositions[]  = new VariancePositionsForm(); 
    }
    VariancePositionsForm::loadMultiple($variancePositions, Yii::$app->request->post());

When I try to var_dump($variancePositions) however, I'm finding that its empty. In other words, loadMultiple() is not loading the models. What am I doing wrong?

Upvotes: 0

Views: 4927

Answers (1)

Ariel Braun
Ariel Braun

Reputation: 86

Because you don't load the model from the form, only from json you have to add an empty string into the last parameter in this function:

VariancePositionsForm::loadMultiple($variancePositions, Yii::$app->request->post(), '');

look here: https://github.com/yiisoft/yii2/blob/master/framework/base/Model.php#L884

Upvotes: 2

Related Questions