How to create Yii2 ActiveForm field with multiple HTML classes

1.3k Views Asked by At

I'm struggling to use Yii2's ActiveForm to create the specific HTML/CSS styling I want. This HTML code below (with css applied) creates a form field with the icon inside of it and the submit button inside.

<form action="" class="form form--type">
            <i class="bpi bpi--icon"></i>
            <input type="email" class="field field--style-round" placeholder="Email address">
            <button type="submit" class="button button--style-default">
              Submit
            </button>
          </form>

Everything between the opening and closing form tags is included in the form. I basically need to create a field for a Yii2 ActiveForm that includes all that html and displays it properly.

I've tried keeping that HTML in place and putting $form->field() where < input type> is but the icon and submit button end up outside of it. Right now, I've tried passing that styling in using textInput($options = []) like this:

<?= $form->field($model, 'email')->textInput($options = 
         [
              'class' =>
                   ['form form--type-input-button-split', 'bpi bpi--email', 'field field--style-round'], 
              'placeholder' => 'Your email address',
              'button' =>
                   ['type' => 'submit', 'class' => 'button button--style-default']
         ])?>

But it doesn't display the icon or submit button inside the field like I need (the button doesn't appear at all). I'm sure I'm not setting up the button right in that array, but in general, how do you create a Yii2 form field with several specific html elements (like < i>, < button>) inside of the form field?

1

There are 1 best solutions below

3
On

You can use parts property and templete property of an active field to configure html of an input, for example:

$form->field($model, 'email', [
  'parts' => [
    '{icon}' => '<i class="bpi bpi--icon"></i>',
    '{button}' => '<button type="submit" class="button button--style-default">Submit</button>'
  ],
  'template' => "{label}\n{icon}{input}{button}\n{hint}\n{error}"
])->textInput($options[
  'class' => 'form form--type-input-button-split bpi bpi--email field field--style-round'], 
  'placeholder' => 'Your email address',
])?>

Also you can configure these property for each field of form, for example:

$form = ActiveForm::begin([
  'id' => 'myform',
  'fieldConfig' => [
    'parts' => [
      '{icon}' => '<i class="bpi bpi--icon"></i>',
      '{button}' => '<button type="submit" class="button button--style-default">Submit</button>'
    ],
    'template' => "{label}\n{icon}{input}{button}\n{hint}\n{error}"
  ],
]);