Activeform - How Do You Call Label, Input, And Errors Individually?

It looks like the new ActiveForm combines the label, input, and error all into one: $form->field($model, $attribute). See code:




<?php $form = ActiveForm::begin([

    'id' => 'login-form',

    'options' => ['class' => 'form-horizontal'],

    'fieldConfig' => [

        'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-7\">{error}</div>",

        'labelOptions' => ['class' => 'col-lg-2 control-label'],

    ],

]); ?>


...


<?= $form->field($user, 'email') ?>



But I need more control over the html/css for proper styling. In Yii 1.xx, you could call them individually like so:




<div class="row">

    <?php echo $form->labelEx($user,'email'); ?>

    <?php echo $form->textField($user,'email',array('size'=>32,'maxlength'=>64)); ?>

    <?php echo $form->error($user,'email'); ?>

</div>



Is there a way to do this in Yii 2?

Yes.




<?= Html::activeLabel($user, 'email'); ?>

<?= Html::activeTextInput($user, 'email'); ?>

<?= Html::error($user, 'email'); ?>



Added it to the guide: https://github.com/yiisoft/yii2/blob/master/docs/guide/form.md

1 Like

Awesome, thanks!

Iā€™m not using Yii2 but from the above code, it seems like these individual methods are no longer part of ActiveForm?

ActiveForm creates an ActiveField instance that calls these methods internally and puts them together according to a template definition. Html::active*() and CHtml::active*() are basically the same thing.

Hi is there a smarter way to create a hidden Field ?




<?php $form = ActiveForm::begin([

        'options' => ['class' => 'form-horizontal'],

        'fieldConfig' => [

            'template' => \common\helpers\ActiveFormHelper::formHorizontalGroupTemplate('col-lg-10'),

            'labelOptions' => [

                'class' => 'col-lg-2 control-label'

            ],

        ]

    ]); ?>




		<?= $form->field($model, 'seo_id',['options' => ['class' => ''],'template' => '{input}',])->input('hidden') ?>


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