Yii2:为单个 $form->textInput() 自定义包装器 div.form-group

Yii2: Customize the wrapper div.form-group for a single $form->textInput()

当我在表单模板中添加 class 时。所有表单组都显示为指定的 class:

/views/user/_form.php

<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;


$disabled_user = !$model->assign_user?'disabled':'';

?>
<?php $form = ActiveForm::begin([
    'options' => ['enctype' => 'multipart/form-data'],
    'fieldClass' => 'app\components\form\FormGroupWidget',
    'fieldConfig' => ['options' => ['class' => 'form-group label-floating']],
]); ?>

但是当我在小部件模板中执行此操作时,并非所有人都想出我分配的 class。

/components/form/FormGroupWidget.php

namespace app\components\form;

use yii\widgets\ActiveField;
use yii\web\View;

class FormGroupWidget extends ActiveField{
    public function textInput( $options = []){

        $this->template ='{label}
                            {input}
                            <div class="error">{error}{hint}
                            </div>
                ';

        $this->form->fieldConfig['options']['class'] = 'form-group label-floating';

        return parent::textInput($options);
    }
}

我想在小部件中配置所有内容,而不是在表单模板中。我不明白为什么它在小部件中不起作用。第一个输入文本没有我的 class 而其他人有:

Result HTML

<div class="form-group">
  <label class="control-label">No. de identificación</label>
  <input type="text" class="form-control" name="UserForm[identification_number]">
</div>

<div class="form-group label-floating">
  <label class="control-label">Nombre</label>
  <input type="text" class="form-control" name="UserForm[name]">
</div>

如果您在 ActiveField

中查看 $options 的文档,则需要使用 $options 而不是覆盖 $form->fieldConfig

@var array the HTML attributes (name-value pairs) for the field container tag. The values will be HTML-encoded using [[Html::encode()]]. If a value is null, the corresponding attribute will not be rendered. The following special options are recognized:

  • tag: the tag name of the container element. Defaults to div. Setting it to false will not render a container tag. See also [[\yii\helpers\Html::tag()]].

If you set a custom id for the container element, you may need to adjust the [[$selectors]] accordingly.

这意味着如果您想要 name=>value 对形式的容器元素,您甚至可以指定 tag 而不是 div

此外,您应该调用父函数,然后从您的函数中覆盖您的设置和 return $this,将函数更改为以下

public function textInput( $options = [] ) {
    parent::textInput ( $options );
    $this->template = '{label}
                        {input}
                        <div class="error">{error}{hint}
                        </div>
            ';
    $this->options=['class'=>'form-group label-floating']
    return $this;
}

希望对您有所帮助