如何在 YII2 中将类添加到 ActiveField 的表单组 div 中?

2022-08-30 23:00:31

我下面有一些代码:

<?=
  $form->field($model, 'phone_no')->textInput(
    [
      'placeholder' =>
      '(Conditionally validated based on checkbox above, groovy!)'
    ]
  )
?>

这将导致 HTML:

<div class="form-group field-contactform-phone_no">
  <label class="control-label">Phone No
  <input type="text" aria-describedby="hint-contactform-phone_no" placeholder="(Conditionally validated based on checkbox above, groovy!)" name="ContactForm[phone_no]" id="contactform-phone_no" class=""></label>
  <small class="error-box"></small>
  <p class="help-text" id="hint-contactform-phone_no"></p>
</div>

我的问题是:

如何将类“不可见”添加到外部 div(当前包含 class=form-group)?

感谢您的帮助


答案 1

您可以对单个字段执行以下操作:

<?= $form->field($model, 'phone_no', ['options' => ['class' => 'form-group invisible'])
    ->textInput(['placeholder' => '(Conditionally validated based on checkbox above, groovy!)']) ?>

全局(对于表单中的所有字段),可能是这样的:

<?php $form = ActiveForm::begin([
    'fieldConfig' => ['options' => ['class' => 'form-group invisible']],
]); ?>

您还可以有条件地构建:fieldConfig

<?php $form = ActiveForm::begin([
    'fieldConfig' => function ($model, $attribute) {
        if (...) {
            return ['options' => ['class' => 'form-group invisible']],
        }
    },
]); ?>

请注意,您还必须包含类,因为它不会与您的自定义类合并。form-group

官方文档:


答案 2

定义所有输入元素的模板布局。

<?php
                $form = ActiveForm::begin([
                            'id' => 'purchase-sms-temp-form',
                            'layout' => 'horizontal',
                            'fieldConfig' => [
                                'template' => " <div class=\"form-group form-md-line-input\">{label}\n{beginWrapper}\n{input}<div class=\"form-control-focus\"> </div>\n{error}\n</div>{endWrapper}",
                                'horizontalCssClasses' => [
                                    'label' => 'col-md-2 control-label',
                                    'offset' => 'col-sm-offset-4',
                                    'wrapper' => 'col-sm-10',
                                    'error' => 'has-error',
                                    'hint' => 'help-block',
                                ],
                            ],
                ]);
                ?>

                <div class="form-body">
                    <?= $form->field($model, 'mobile') ?>
                    <?= $form->field($model, 'volume') ?>
                    <?= $form->field($model, 'hospital_id') ?>
                    <?= $form->field($model, 'created_date') ?>
                    <?= $form->field($model, 'complete') ?>
                    <?= $form->field($model, 'modified_date') ?>

                </div>

对于自定义字段,您可以通过以下方式定义类:

$form->field($model, 'phone_no', [
          'options' => [
             'class' => 'form-group invisible'
           ])->textInput([
              'placeholder' => '(Conditionally validated based on checkbox above, groovy!)']) ?>

推荐