Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 ActiveForm fields options does not work

Tags:

php

yii2

According to the official tutorial of Yii2. I have created a view for the entry form:

    <?php
    use yii\helpers\Html;
    use yii\widgets\ActiveForm;
    ?>
    <?php $form = ActiveForm::begin(); ?>
<!-- GET Attention for the next Line -->
    <?= $form->field($model, 'name')->label('Your Name'); ?>
    <?= $form->field($model, 'email'); ?>
    <div class="form-group">
      <?=  Html::submitButton('Send!', ['class' => 'btn btn-primary']); ?>
    </div>    
    <?php ActiveForm::end(); ?>

At this point everything is well fine. However, when I try to use the parameter options of the field method as follows:

<?= $form->field($model, 'name', ['style' => 'color:red'])->label('Your Name'); ?>

I have got the error:

Unknown Property – yii\base\UnknownPropertyException

Setting unknown property: yii\widgets\ActiveField::style

The official api documentation stated that method of ActiveForm takes a third parameter called options

Could anybody explain me why this error has been occurred?!

like image 305
SaidbakR Avatar asked Dec 15 '14 00:12

SaidbakR


3 Answers

Try

<?= $form->field($model, 'name')->textInput(['style' => 'color:red'])->label('Your Name'); ?>

It is a little hard to explain, when you do $form->field($model, 'name') without specifying the field type you are actually asking for a textInput. But that does not mean that you should ask from ->field( to take the params the same way as ->textInput( does. If you need to put some special params for the field you have to use the explicit ->textInput(['style' => 'color:red'])

like image 140
Mihai P. Avatar answered Nov 08 '22 18:11

Mihai P.


This way is for especify options on all the "field" (that includes the "label" and the "input") but 'style'=>'color:red' only affects to label in this way, I use this for especify class options instead of color:

<?= $form->field($model, 'name', [ 'options' => [ 'class' => 'col-xs-8']])->label('Your Name'); ?>

If you want to especify options for one of them (label or input)you can do it separately, like this:

<?= $form->field($model, 'name')->textInput(['style' => 'color:red'])->label('Your Name',['style'=>'color:blue']); ?>

Yii is so flexible, that is what i like of it.

like image 30
Jose Manuel Kun Avatar answered Nov 08 '22 17:11

Jose Manuel Kun


Try this code:

<?= $form->field($model, 'name', [ 'options' => [ 'style' => 'color: red']])->label('Your Name'); ?>

You've got this error

Unknown Property – yii\base\UnknownPropertyException

Setting unknown property: yii\widgets\ActiveField::style

because there is no such property style. You should use 'options' and pass 'style' as sub-array

like image 9
tsanchev Avatar answered Nov 08 '22 18:11

tsanchev