欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

add class to form element


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?

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')),
    );
   }
shareimprove this answer
 
   
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
1 
You should add an element to the class array, instead of overwriting it. Example : $form['name']['#attributes']['class'][] = 'form-control'; – Jonathan Bergeron Sep 8 '16 at 14:49

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.

shareimprove this answer
 

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'));
shareimprove this answer
 

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'))))
);

来自  http://drupal.stackexchange.com/questions/81405/add-class-to-form-element
普通分类: