3

I am creating a custom module. I have a form that I would like to add some HTML to, but I don't know what the best way to do this.

In this example, I have a page with a textbox, dropdown list, and text area. I want to add a a div between the dropdown list and text area. But, I'm not sure how to add raw html to a web form.

Here is what I have:

function myModule_add_form($form_state){
  try{
    $form = array();
    $form['myModule_title'] = array(
      '#title' => 'Title',
      '#type' => 'textfield',
      '#size' => '30',
      '#weight'=>1,
    );

    $form['myModule_type_list']=array(
      '#type'=>'select',
      '#title' => 'Type List',
      '#options' => $someArray,
      '#multiple' => false,
      '#attributes'=>array('size'=>1),
      '#weight'=>2,
    );

    $form['myModule_description'] = array(
      '#title' => 'Description',
      '#type' => 'textarea',
      '#size' => '255',
      '#weight'=>3,
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Submit',
      '#weight'=>4,
    );

    return $form;
  } catch(Exception $e){
      $errrmsg = "Error with creating form: " .$e->getMessage();
      throw New Exception($errrmsg);
  }
}

Thanks jason

3 Answers 3

0

You need #type => markup here as per Form API.

$html = '<strong>My HTML</strong>';

$form['mymarkup'] = array(
  '#type' => 'markup'
  '#value' => $html,
);
1
  • 1
    This answer is not correct. There's a syntax error in the code provided (missing comma) and it's supposed to be #markup rather than #value, at least in drupal 8. Sep 1, 2020 at 19:55
6

No need to declare a form element as #type = 'markup', as this is the default type.

$html = '<strong>My HTML</strong>';

$form['mymarkup'] = array(
  '#markup' => $html,
);

Refer to: https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x

1
  • This should get the correct answer checkmark. Sep 1, 2020 at 19:55
2

Try this instead:

$html = '<strong>My HTML</strong>';

$form['mymarkup'] = array(
  '#type' => 'markup',
  '#markup' => $html,
);

Refer to: https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x

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.