10

I am following this tutorial and I've already created my custom form as Drupal 8 module.

I wonder, how to add custom text/html in form? I mean when somebody goes to the path pointed in *.routing.yml, I would like to display not only form fields, but also some intro html/text.

I know the form building is here:

public function buildForm(array $form, FormStateInterface $form_state) {

$form['name_surname'] = array(
  '#type' => 'textfield',
  '#title' => t('Name and surname:'),
  '#required' => TRUE,
);
...
}

But I don't know what kind of entry (or #type) should I insert to get just an custom html/text block between fields or above them all?

3 Answers 3

7

#field_prefix #field_suffix and #description should do the trick. Here's more info about FormElement. I believe you can also set an element to type markup and then use #markup to create an element that's just HTML (see ya.teck's answer).

2
  • 2
    #type markup has been removed drupal.org/node/2036237
    – ya.teck
    Commented Nov 3, 2016 at 7:27
  • To clarify to those who might not click ya.tect's link, '#markup' => '<b>foo</b>' still exists, you just dont need to specify, '#type' => 'markup' anymore.
    – Jeff
    Commented Oct 3, 2018 at 17:22
25

What kind of entry (or #type) should I insert to get just an custom html/text block between fields or above them all?

Item element type provides a display-only form element with an optional title and description.

$form['help'] = [
  '#type' => 'item',
  '#title' => t('Block title'),
  '#markup' => t('Block content'),
];

You may also add arbitrary content to render arrays using the #markup render array key as follows.

$form['text']['#markup'] = t('Some text.');
1
  • This is handy, but beware: it won't work for unrecognized tags. Ex: <foo></foo>. I haven't figured out a way to do this yet. Commented Nov 13, 2017 at 11:53
2

With Using markup you can add Html markups into your form.for an instance :

$form['help'] = [
    '#type' => 'markup',
    '#markup' => '<a href="#">Find out more</a>',
    '#weight' => '3',

];
2
  • drupal.org/node/2036237 - Not sure if you saw the comment earlier. Although the code will work as type markup will not have any effect.
    – anoopjohn
    Commented Nov 17, 2019 at 6:34
  • Drupal just strips any HTML out of the '#markup' key, anyone know if there's a fix for this?
    – TedMilker
    Commented Aug 5, 2020 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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