7

I have my form, but any child of the "#markup" element will not appear when the form is being rendered.

$form['html'] = array(
  '#type' => 'markup',
  '#markup' => '<h2>My Heading</h2>',
  '#tree' => true,
);

$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
);

In this example the "element" form field will not be rendered.

Is this a Drupal bug, or do I need to do something specific?

  • It is not a bug, it is a misconception. One cannot inject other elements in a markup text. Instead create a container and add the markup and the textfield there. – Neograph734 Jun 21 '16 at 20:26
8

Not being able to use "#tree" with a "#markup" element seems a bug of Drupal, as the reference page for the form API reports that "#tree" is supported by the "#markup" element.

As workaround, you can also use the "#prefix" property, as in the following code:

$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
  '#prefix' => '<h2>My Heading</h2>',
);

If it is not rendered as you expect, then you can simply remove "#tree" from your code, which doesn't seem to be needed, if all you want is to render the <h2>My Heading</h2> tag before the form fields. The form API renders the elements following the order they appear in the array; if you want to alter the order, you can use the "#weight" property.

$form['html'] = array(
 '#type' => 'markup',
 '#markup' => '<h2>My Heading</h2>',
);

$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
);
  • Thanks, but I do need the tree element as my actual form is a little more sophisticated than the above example. I'm also trying to avoid using prefix/suffix markup values in order to keep to code cleaner and such. My form consists of a few loops generating a tree structure of elements with a depth of about 4. If the 'markup' element type can't have children than I'll have to restructure some of my form. – user1589 Aug 26 '11 at 12:59
  • It seems a bug of Drupal, as the "markup" element is supposed to be able to use "#tree"; what I reported are the only workarounds/alternatives I know of. – kiamlaluno Aug 26 '11 at 14:13
  • 1
    I opened a issue report: drupal.org/node/1261040. The referring version is 8.x because the bugs are first fixed in Drupal 8, and then back ported to the previous versions. – kiamlaluno Aug 26 '11 at 14:24
1

To be a little more precise, the children of #markup type elements are not rendered. They are processed for form purposes, though.

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.