Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the 'triggering element' in $form_state is the last button on the form?

I have mymodule_field_widget_form(), that creates an auto complete text field, and 3 buttons for a custom field. On 2 buttons I'm using ajax callback functions that invoke custom ajax commands. When function execution enters the callback function of either buttons, the $form_state['triggering_element'] is always the same, the last button (form element...?) in the form that was created by the hook above. I would like to get the element that actually triggered the callback. It is possible, the this custom field is added to a content type more than once, and that is why it is important. The custom ajax command creates a jQuery ui dialog with an iframe or plain html content in it, depending on several factors, so I thought it is not necessary to re-render the whole form in which the button was triggered. Actually there is no re-rendering anywhere, maybe that is the problem?

like image 588
Temaruk Avatar asked Jun 29 '11 12:06

Temaruk


2 Answers

Set the #default_value as Spudley recommended and set the #name attribute to something unique (use the $delta parameter).

like image 129
tamasd Avatar answered Sep 23 '22 03:09

tamasd


When function execution enters the callback function of either buttons, the $form_state['triggering_element'] is always the same, the last button

This is unfortunately how Drupal's form API works. If you have several submit buttons on a form, you sometimes can't tell which one was clicked.

Firstly, see this answer on Drupal.org which I think might help you:

Look in your form setup code. Where you're defining the various buttons, change '#value' into '#default_value'. This will allow Drupal to recognise that the field value (ie the form submit value) can change, and therefore it won't be fixed to the value of the last button, regardless of which one was clicked.


If that doesn't help, here are a few other solutions that might help:

  1. Look directly at PHP's $_POST array to find out which button was clicked. This works, but goes against "The Drupal Way". The whole point of Drupal's form API is to hide the raw PHP functionality from you. But at times like this it may be useful to take a peep at it.

  2. Put the buttons into separate forms. This obviously would only work if you don't need any of the other fields to be submitted at the same time.

  3. Create a hidden field on your form, and use Javascript to populate it with the name of the clicked button, immediately prior to submitting the form.

Hope that helps.

like image 30
Spudley Avatar answered Sep 23 '22 03:09

Spudley