6

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?

6

#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
    #type markup has been removed drupal.org/node/2036237 – ya.teck Nov 3 '16 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 Oct 3 '18 at 17:22
13

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.');
  • 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. – emersonthis Nov 13 '17 at 11:53
0

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',

];

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.