Drupal form with custom id

Correct me if I'm wrong, after reading the articles related to drupal fapi, I got the impression that fapi generates id attributes by itself. This allows developers to assign only the name attribute. If so, is there a way to set the id value for the elements? Because I want my elements to have a meaningful "id" so that the html / jquery code is easier to read and also save my time from going through the jquery code already written to change all the "ids" I used internally.

PS: drupal version is 6.x

+2


a source to share


4 answers


Found a solution well. I can use the #attributes

element key $form

to set any additional attributes (like class, id, etc.). Thanks for your help.



+2


a source


I had a similar problem. I needed to have multiple forms on the same page, so I had to change the IDs of the form and its elements to prevent duplicate IDs. I did something like the following:

function voci_comment_form($form, &$form_state, $cid) {
  $form['#attributes']['id'] = 'voci-comment-form-' . $cid;
  $form['#attributes']['class'][] = 'voci-comment-form';
  $form['body'] = array(
    '#title' => 'Post a comment',
    '#type' => 'textarea',
    '#resizable' => FALSE,
    '#rows' => 1,
  );
  $form['comment'] = array(
    '#type' => 'submit',
    '#value' => 'Comment',
  );

  foreach ($form as $k => &$element) {
    $k = str_replace('_', '-', $k);
    $element['#attributes']['id'] = "edit-$k-$cid";
    $element['#attributes']['class'][] = "edit-$k";
  }

  return $form;
}

      



It basically sets up unique IDs based on the $ cid passed in. The code also adds classes to each form element so that you can style it easily. I'm sure a more robust solution is possible, but that's the main idea. Tested in Drupal 7.

+1


a source


It is true that you can set $element['#attributes']['id']

and this applies to the form field. However, it breaks labels #states

on Drupal 7 too , because the rest of the rendering pipeline reads the ID from elsewhere. So to keep your labels up and #states

running, use an ID instead $element['#id']

(an undocumented property that is nevertheless how the form API looks at IDs internally).

Make sure to pass your ID through drupal_html_id

to avoid conflicts.

+1


a source


This issue has little to do with Drupal-FAPI itself, but more about how Drupal forms shape (create markup).

  • If you want to change all the forms on your site, you can overwrite the abstract functions that are used for different types of forms and fields.

  • If you just want to overwrite some form or form fields, you can set an attribute #theme

    on the form or element to change which function should be used to generate the markup.

0


a source







All Articles