Split ActiveForm fields into different tabs with Tabs widget

AleCat83 picture AleCat83 · Feb 2, 2015 · Viewed 8.2k times · Source

I'm creating a form view and I want to organize the form fields with tabs structure, using the official Tabs widget.

Is it possible init the Tabs widget with the id (or class) of the div elements that contains the active form fields?

Answer

Jørgen picture Jørgen · Mar 16, 2015

One example of how you can manage it is doing like this:

  1. First, divide your contact-form into one view-file for each tab.
  2. Place the ActiveForm::begin() and ActiveForm::end() around the Tabs::widget()
  3. Render the contact-form pages into content, with parameters $model and $form

Example code:

views/site/contact.php

<?php

/* @var $this yii\web\View */
$this->title = 'Contact';

use yii\bootstrap\Tabs;
use yii\bootstrap\ActiveForm;
?>


<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= Tabs::widget([
        'items' => [
            [
                'label' => 'One',
                'content' => $this->render('contact_form1', ['model' => $model, 'form' => $form]),
                'active' => true
            ],
            [
                'label' => 'Two',
                'content' => $this->render('contact_form2', ['model' => $model, 'form' => $form]),
            ],
        ]]);
 ?>
    <?php ActiveForm::end(); ?>

views/site/contact_form1.php

<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'subject') ?>

views/site/contact_form2.php

<?php
use yii\helpers\Html;
use yii\captcha\Captcha;
?>

<?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
    'template' => '<div class="row"><div class="col-lg-3">{image}</div><div    class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>

Hope this helps!