[Drupal] How to implement confirmation form in Drupal 7

| | 2 min read

Confirmation form is useful in cases where we do some action that needs confirmation from the user. Drupal provides a function called confirm_form() that provides a confirmation form.

The confirm form contains a confirm button for confirming the action and a cancel link for cancelling the action. There should be a submit handler for the confirm submit button which do the corresponding actions. And the cancel link can be set to redirect to a page.

The following example shows the usage of confirm function.

Consider a menu "activity/%/delete".


  $items['activity/%/delete'] = array(
    'title' => 'Delete activity',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_delete_activity_form', 1),
  );

The function in the page arguments provides the confirm form, which is passed as argument to the drupal_get_form. The "my_module_delete_activity_form" shows the way of using the confirm function.

The function confirm_form() has the following arguments.

  • The form elements: This argument specifies the form elements in the confirm form. We can add additional form elements if we want.
  • The question: This argument specifies the confirmation question.
  • The cancel path: This argument specifies the path to which the cancel link redirects.
  • Description: This argument specifies the additional text to display in the confirm form.
  • Confirm submit button caption: It specifies the confirm button Caption.
  • Cancel link caption: It specifies the cancel link caption.
  • Reference name: It specifies the reference name for the confirmation item.

The following example function shows the usage of confirm_form


  function my_module_delete_activity_form($form, &$form_state) {
    global $base_url;
    $account_id = arg(3);
    $form = confirm_form($form,
      'Are you sure, Do you want to delete?',
      'activity-list',
      'The action cannot be undone.',
      'Delete',
      'Cancel',
    );
    return $form;
  }
  

When the "Delete" button in pressed the submit handler written for the confirm_form is called. The cancel link here redirects to the page activity-list. The submit handler can be like:


function my_module_delete_activity_form_submit($form, &$form_state) {
  // Required actions here
}

There is no argument in the function confirm_form to redirect to a page after the action is confirmed. For this we can specify a drupal_goto() in the submit handler of the confirm_form to redirect after the action is complete.