Drupal 7: confirm_form() als Sicherheitsabfrage

Autor: Sven am Wed, 12.11.2014 - 11:26

Hier mal ein Demomodul wie man eine Sicherheitsabfrage vor dem Löschen eines Eintrages aus der Datenbank einbindet, ein entsprechendes Datenbankschema via example.install vorrausgesetzt. Fragen bitte über die Kommentare oder per Mail.

/**
 * Impelemts hook_menu().
 */
function example_menu() {
  $items = array();
  $items['example/%/delete'] = array(
    'title' => 'Delete item',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('example_item_delete', 1),
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Delete item from db
 */
function example_item_delete($form, &$form_state, $id) {
  $form = array();
  $form['id'] = array('#type' => 'value', 'value' => $id);

  $question = t('Are you sure you want to delete %id?', array('%id' => $id));
  $path = '<front>'; // The path where to go when hitting "Cancel"
  $undone = t('This action cannot be undone.');
  $delete = t('Delete');
  $cancel = t('Cancel');

  return confirm_form($form, $question, $path, $undone, $delete, $cancel);
}

/**
 * Implements hook_form_submit().
 */
function example_item_delete_submit($form, &$form_state) {
  // Delete entry from database
  db_delete('example')->condition('id', $form_state['values']['id'])->execute();

  // Show a message to user
  drupal_set_message(t('Entry was deleted from db'));

  // Redirect to front page
  $form_state['redirect'] = '<front>';
}