2

I have a strange behavior (or at least this is what I think) I have two form elements. Both are required, in the first (First Name) I want to have a required field so I use '#required' => TRUE and '#required' => TRUE in the second I don't use this properties to says that the field is required, I just add this line to the title '<span class="form-required" title="' . t('This field is required.') . '">*</span>'. The problem is that the output of the first element is "First name " (with space at the end) and in the second element the output is "Last name" (without space at the end). See the code and the picture with the output code.

Is this a normal behavior or I missing something here?

  $form['general']['group-1']['prenom'] = array(
    '#prefix' => '<div class="item">',
    '#title' => t('First name'),
    '#id' => 'cf-1',
    '#type' => 'textfield',
    '#required' => TRUE,
    '#attributes' => array('required' => 'required'),
    '#suffix' => '</div>',
  );

  $form['general']['group-1']['nom'] = array(
    '#prefix' => '<div class="item">',
    '#title' => t('Last name') . '<span class="form-required" title="' . t('This field is required.') . '">*</span>',
    '#id' => 'cf-2',
    '#type' => 'textfield',
    '#suffix' => '</div>',
  );

The HTML code:

enter image description here

3

Works as designed imho.

The markup of the first is generated by the form element/Drupal. By default Drupal has a space between the field title and the asterisk. That's just how it was designed.

The second time you tell the form what to add - exactly what to add. Drupal wont add a space for you, as you may not always want a space between your custom wrapper and the title. (In most cases you probably don't.)

If it is important to remove the space you can overwrite theme_form_element() in your theme. Check the mid to late replies (starting with kkatusic) in this thread: How to remove asterisks from required fields?

Is there a reason why you would want to mark a field required if it isn't a required field?

2
  • This is just an example. But the really reason is because I need to make some validations with javascript so I put the asterisk for indicate that the field is required. Thanks for your answer. Jul 8 '16 at 17:00
  • 1
    Well, if it is important to remove the space you can overwrite theme_form_element() in your theme. Check the mid to late replies (starting with kkatusic) in this thread: drupal.org/node/141790
    – Zuzuesque
    Jul 8 '16 at 17:06

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.