2017-06-14 86 views
0

如何創建一個相同表單的動態列表並在Yii2的視圖上顯示它(它可以被視爲具有不同信息的同一對象的列表)謝謝。如何在Yii2上創建相同表單的動態列表?

我在/frontend/views/site/example.php上有下列表格: 我想把它放在一個列表中。

<div class="site-example"> 
    <h1><?= Html::encode($this->title) ?></h1> 
    <p>Example of a list:</p> 

    <div class="row"> 
     <div class="col-lg-5"> 
      <?php $form = ActiveForm::begin(['id' => 'form-example']); ?> 

       <?= $form->field($model, 'email')->textInput(['readonly' => true, 'value' => $email]) ?> 

       <?= $form->field($model, 'lastname')->textInput(['readonly' => true, 'value' => $lastname]) ?> 

       <?= $form->field($model, 'phone')->textInput(['readonly' => true, 'value' => $phone]) ?> 

      <?php ActiveForm::end(); ?> 
     </div> 
    </div> 

</div> 

回答

0

假設這是你的controller

<?php 

namespace frontend\controllers; 

use Yii; 
use yii\base\Model; 
use yii\web\Controller; 
use frontend\models\YourForm; 

class SiteController extends Controller 
{ 
    public function actionYourAction() 
    { 
     $forms = [new YourForm, new YourForm, new YourForm]; 

     return $this->render('example', [ 
      'forms' => $forms 
     ]); 
    } 
} 

然後你view可能低於

<div class="site-example"> 
    <h1><?= Html::encode($this->title) ?></h1> 
    <p>Example of a list:</p> 

    <div class="row"> 
     <div class="col-lg-5"> 
      <?php foreach ($forms as $index => $form): ?> 
       <?php $form = ActiveForm::begin(['options' => ['id' => "form-example-$index"]]); ?> 

        <?= $form->field($form, "[$index]email")->textInput(['readonly' => true, 'value' => $form->email]) ?> 

        <?= $form->field($form, "[$index]lastname")->textInput(['readonly' => true, 'value' => $form->lastname]) ?> 

        <?= $form->field($form, "[$index]phone")->textInput(['readonly' => true, 'value' => $form->phone]) ?> 

       <?php ActiveForm::end(); ?> 
      <?php endforeach; ?> 
     </div> 
    </div> 
</div> 
+0

我可以做控制器上的以下? $ model = new MyForm(); $ forms = [$ model,$ model,$ model]; –

+0

嗨@JanBeeck,我剛剛嘗試過你的情況,而且效果很好。 – paul

+0

感謝@paul的答案。所以上面的代碼可以使用3種形式。 –