Drupal - How can I know which button was clicked?
You must use $form_state->getTriggeringElement()
.
Best practice is to define a #name
attribute for your button, so you can have this value in the triggering_element
.
For example:
$form['delete'] = array(
'#type' => 'submit',
'#value' => t('Delete'),
'#name' => 'delete',
);
In this example:
$form_state->getTriggeringElement()['#name']
will return "delete" when called within public function submitForm(&$form, $form_state)
If you don't define this attribute triggering_element
will hold the button's #value
(the text that user can read), but this is discouraged as other modules may change this value or be changed by the localization).
You may use $form_state['clicked_button']
too, but this is deprecated.
You can read more info at the drupal_build_form function documentation page.
$form_state['clicked_button']['#value']
will tell you which button was clicked on the form.
Compare these values in $form_state
I have been doing in Drupal 6 and would be same in Drupal7
if($form_state['values']['ok'] == $form_state]['clicked_button']['#value']){
//Process if OK is pressed
}else if($form_state['values']['cancel'] == $form_state]['clicked_button']['#value']) {
//Process if Cancel is pressed
}