0

How to add html tag in a form element drupal 8?

$form['buttons']['submit'] = [
  '#type' => 'submit',
  '#value' => T('Send'),
  '#prefix' => '<div class="modal-footer">',
  '#suffix' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">' . $this->t('Close') . '</button></div>',      
  '#attributes' => [
    'class' => ['btn-success'],
  ]
];

I try to add allowed_tags:

$form['buttons']['submit'] = [
  '#type' => 'submit',
  '#value' => T('Send'),
  '#prefix' => '<div class="modal-footer">',
  '#suffix' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">' . $this->t('Close') . '</button></div>',
  '#allowed_tags' => ['button'],
  '#attributes' => [
    'class' => ['btn-success'],
  ]
];

OR

$form['buttons']['#allowed_tags'] = ['button'];
$form['#allowed_tags'] = ['button'];

Not working... Help me please!

3

I can't tell which element is giving you trouble.

For the div, instead of prefix/suffix you can create a container element:

$form['submit_container'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => ['modal-footer'],
  )
);

And then you can put a submit input inside of that:

$form['submit_container']['submit'] = array(
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes' => array(
    'class' => ['btn', 'btn-sm', 'btn-default'],
    'data-dismiss' => 'modal',
  )
);

If you need a button type='button' just to fire Javascript and not submit the form, that is somewhat problematic, it seems. One method is to override the button template.

Type inline_template may be the best bet:

$form['submit_container']['button'] = array(
  '#type' => 'inline_template',
  '#template' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal" onclick="closeButton()">Close</button>',
);

Change a normal submit 'input' type to 'button' type with button tag

1

If you are looking to add a custom HTML tag use the new type in the form api html_tag, here's an example from the form API documentation :

$build['hello'] = [
  '#type' => 'html_tag',
  '#tag' => 'p',
  '#value' => $this->t('Hello World'),
];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.