Avi
Avi

Reputation: 117

Yii2 how to send multiple instances of a model to one form? & get them back in the controller

I tried some ways: first I created some instances in controler & sent them to the form but when I get them back in the controller I get just the last one. then I tried to use this way: in the controller:

$models = [new BannerAd()];
    for($i = 1; $i < 4; $i++) {
        $models[] = new BannerAd();
    }

after in the view (form):

<div class="banner-ad-main container">
<?
$form1 = ActiveForm::begin();
echo 'One model';
echo $form1->field($models[0], "[0]banner_ad_url")->label($models[0]->banner_ad_img);
echo 'Second model';
echo $form1->field($models[1], "[0]banner_ad_url")->label($models[1]->banner_ad_img);
echo 'Third model';
echo $form1->field($models[2], "[0]banner_ad_url")->label($models[2]->banner_ad_img);
?>
<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<? ActiveForm::end(); ?>

But still I get in the $post just the last one.

This is what I get

Thank you

Upvotes: 0

Views: 512

Answers (1)

Avi
Avi

Reputation: 117

Sorry I had a mistake. I forgot to change the index in the form. this is the right code:

 echo $form1->field($models[0], "[0]banner_ad_url")->label($models[0]->banner_ad_url);
    echo $form1->field($models[1], "[1]banner_ad_url")->label($models[1]->banner_ad_url);
    echo $form1->field($models[2], "[2]banner_ad_url")->label($models[2]->banner_ad_url);

Upvotes: 1

Related Questions