2

I want to add a CSS class to the input element of a custom field in my user_register_form.

This is the field markup.

<div class="field-type-text field-name-field-personal-best field-widget-text-textfield form-wrapper"
 id="edit-field-personal-best">
<div id="field-personal-best-add-more-wrapper">
    <div class="form-item form-type-textfield form-item-field-personal-best-und-0-value">
        <label for="edit-field-personal-best-und-0-value">Personal Best </label>
        <input class="text-full form-text" id="edit-field-personal-best-und-0-value"
               name="field_personal_best[und][0][value]" value="" size="60" maxlength="255" type="text">
    </div>
</div>

This is my implementation of hook_form_alter(), which doesn't work. Changing the submit button works, but adding a CSS class to that input element doesn't.

function em_form_alter(&$form, &$form_state, $form_id) {    
if ($form_id == 'user_register_form') {
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['edit-field-personal-best']['#attributes']['class'][] = 'timepicker hasDatepicker';
}}

How can I achieve this?

3

Looks like you're trying to use the HTML ID of the element you're interested in as the identifier in PHP - not quite how it works.

For a field API field, that will look more like:

$form['field_personal_best'][LANGUAGE_NONE][0]['value']['#attributes']['class'][] = 'foo';

Your mileage will probably vary there, have a read of Why is hook_form_alter() so messy? for some relevant information, and make sure you have the Devel module installed to help with debugging (dpm($form) will tell you pretty much everything you need to know).

  • Thanks mate, that helped, spent so much time yesterday trying to figure this out. Btw i have devel installed but (dpm($form) doesnt work as im not logged in when checking register page. Or am i doing that wrong too. – Alex Mar 9 '14 at 10:58
  • Ah ok, if this is a dev site you can set a permission for anon users to see Devel output - don't enable it on a production site though, and remember to turn it back off again (or ideally uninstall Devel altogether) when you go live – Clive Mar 9 '14 at 11:02

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.