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

这里的技术是共享的

You are here

drupal form attributes add class Adding class to form-item 表单元素字段增加 class

 

I've been trying to add a custom classname to a form-item to use as a 'marker' for theming with my css file.

I've been on stackexchange/overflow and several other sites and forums, including the Drupal documentation, but found no reason why it shouldn't work.

Official documentation state the use of the attribute tag like so:

'#attributes' => array('class' => 'myclass'),

But as seen in my example below, this doesn't work or give me errors.

screenshot

Am I doing something wrong?

shareimprove this question
 

#attributes is not supported by item form elements.

item

Description: Generate a display-only form element allowing for an optional title and description.

Note: since this is a read-only field, setting the #required property will do nothing except theme the form element to look as if it were actually required (i.e. by placing a red star next to the #title).

Properties: #access, #after_build, #description, #element_validate, #parents, #post_render, #prefix, #pre_render, #required, #suffix, #theme, #title, #tree, #type, #value, #weight

You would then need to add a custom theme call such as:

function MYTHEME_preprocess_form_element(&$vars)
{
$vars['#attributes']['class'][] = 'another-class';
}

shareimprove this answer
 
   
You're absolutely correct, how could i've not seen this. However this puts me even further from my end goal :( I did however found a different article here (stackoverflow.com/questions/5012870/…) that could help me, but i think i'm doing something wrong with it. I created a file named sgv_inschrijving_node_form.tpl.php (same name as the file in the module that renders the form) in the template folder of my theme with the following code:i.snag.gy/doRBg.jpg – Donaldini Jun 15 '12 at 11:55
 

In the end, I solved it by adding code to the .module file. I wrapped a div with class around the content.

shareimprove this answer
 
1 
If you are adding code to core module files, this is a very very bad idea. You will no longer be able to update this module without your site breaking. – Sam152 Jun 18 '12 at 15:09

You could use _form_set_class()

Docs: https://api.drupal.org/api/drupal/includes!form.inc/function/_form_set_class/6.x

Example:

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

for the future, if you use the #attributes, wrap the class name(s) in an array like this:

'#attributes' => array('class' => array('myclass', 'otherclass')),


 来自  http://drupal.stackexchange.com/questions/34175/adding-class-to-form-item

普通分类: