8
function ajax_register_form_user_login_alter(&$form, &$form_state, $form_id) {
   $form['fbuser'] = array(
      '#type' => 'item',
      '#markup' => 'You have a facebook account?',
      '#weight' => -10,
    );
   $form['login_link'] = array(
      '#type' => 'item',
      '#markup' => '<a class="facebook-action-connect" rel="nofollow" href="foo"><img src="foo" alt=""></a></div>',
      '#weight' => -6,      
    );
   }

How can I add a class to this div's?

1
  • Have a look at the answer to this question. You might need to preprocess theme_form_element instead (totally depends what you need to do), but that's the basic idea
    – Clive
    Aug 3 '13 at 17:55
13

You might be looking for the #attributes property that you can add to forms and form elements. See example below

function ajax_register_form_user_login_alter(&$form, &$form_state, $form_id) {
   $form['fbuser'] = array(
      '#type' => 'item',
      '#markup' => 'You have a facebook account?',
      '#weight' => -10,
      '#attributes' => array('class' => array('my-class-1')),
    );
   $form['login_link'] = array(
      '#type' => 'item',
      '#markup' => '<a class="facebook-action-connect" rel="nofollow" href="foo"><img src="foo" alt=""></a></div>',
      '#weight' => -6,
      '#attributes' => array('class' => array('my-class-2')),
    );
   }
3
  • it seems right, but it doesn't work. maybe it's ajax login/register module cache or some settings. i don't know
    – AlexEfremo
    Aug 4 '13 at 14:28
  • 2
    You should add an element to the class array, instead of overwriting it. Example : $form['name']['#attributes']['class'][] = 'form-control'; Sep 8 '16 at 14:49
  • #attributes is not working with item type, see documentation! (api.drupal.org/api/drupal/…) Jun 15 '17 at 16:35
6

According to the drupal official form api guide, the item type cannot use the #attributes property:

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#item

A workaround could be using the #prefix and #suffix properties:

$form['fbuser'] = array(
  '#type' => 'item',
  '#markup' => 'You have a facebook account?',
  '#weight' => -10,
  '#prefix' => '<span class="my_class">',
  '#suffix' => '</span>', // close the span openend by the #prefix property
);

The drawback is that the css class will be added to a parent of the item element, not to the item itself.

1

Use '#attributes' => array('class' => array('my-class')) or else you can do this:

$form['html_markup_address'] = array(
  '#markup' => l(t('Add New Address'), 'mymodule/nojs',
   array('attributes' => array('class' => array('ctools-use-modal'))))
);
0

You could use _form_set_class()

Docs: https://api.drupal.org/api/function/_form_set_class/7.x

Example:

_form_set_class($element, array('my-class'));

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.