0

I have menu callback which is getting called multiple times on the same page by an AJAX request resulting rendering the form with same HTML id

$items['mymodule/page'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('page_callback_form'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

function page_callback_form($form, &$form_state, $thing) {
  $form['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Message'),
    '#cols' => 80,
    '#rows' => 5,
  );
  return $form;
}

Result:
<textarea id="edit-message" name="message" cols="80" rows="5" class="form-textarea"></textarea>

<textarea id="edit-message" name="message" cols="80" rows="5" class="form-textarea"></textarea>

i was wondering is there a way i can have unique Ids, i have tried [hook_forms].1

3
  • There is no existing API for that purposes. You can implement one by yourself. It should not be difficult. You can come up the idea easily by forking 'drupal_get_form'
    – Jimmy Ko
    Commented Jul 24, 2016 at 10:27
  • You should consider changing your logic so it's just one form, with the new message field added using the AJAX API. Then Drupal will take care of the unique IDs for you
    – Clive
    Commented Jul 24, 2016 at 12:38
  • BTW, your function signature is wrong (it's currently nearly Drupal 6 code), it should be: function page_callback_form($form, &$form_state, $thing), and remove the $form = array(); line
    – Clive
    Commented Jul 24, 2016 at 12:47

1 Answer 1

0

You can do it!

With the drupal fapi. You can overload every HTML attributes by using the element #attributes.

Exemple:


  $form['form_element'] = array(
    '#type' => 'textfield',
    '#title' => t('If you Have a Code, Redeem it here:'),
    '#attributes' => array(
      'id' => 'your_id',
    ),
  );

If you add a counter or something to your id, you will have a different id for each fields.

Cheers

3
  • As same callback is running again and again so whatever counter you put that will give the same id.
    – mks
    Commented Jul 25, 2016 at 6:02
  • Yes, you are right. The same hook will be called. But the question is: how can I have different ids for every textfield.The solution I suggest answer the question. And yes the question seems not complete :/
    – Denis K
    Commented Jul 25, 2016 at 6:31
  • It is not a complete solution. And, I think Drupal can handle the duplicated ID by itself with appending '--1'.
    – Jimmy Ko
    Commented Jul 25, 2016 at 7:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.