background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount
Eric.London's picture

In a module I was developing recently, I needed to add a javascript confirm popup before allowing the user to submit the form. Here is an excerpt from my code to show you how to add the jQuery

<?php
function MYMODULE_main() {
 
$page_contents  = "";
 
// ...code...
 
$page_contents .= drupal_get_form('MYMODULE_form');
 
// ...code...
 
return $page_contents;
}

function
MYMODULE_form() {
 
$form = array();
 
// ...code...
 
$js = "
    $(document).ready(function(){
      $('#"
. str_replace('_','-',__FUNCTION__) . "').submit(function(){
        if (confirm('Are you sure?')) {
          return true;
        } else {
          return false;
        }
      );
    });
  "
;
 
drupal_add_js($js, 'inline');
 
// ...code...
 
return $form;
}
?>

Eric.London's picture

Here is a way to globally replace all the cancel links on the confirm delete node pages...

<?php
function MYMODULE_form_alter($form_id, &$form) {
 
// ...code...
 
if ($form_id == 'node_delete_confirm') {
   
_MYMODULE_form_alter_node_delete_confirm($form);
  }
 
// ...code...
}

function
_MYMODULE_form_alter_node_delete_confirm(&$form) {
  if (
is_array($form['actions']['cancel'])) {

   
// convert the html from the link into an xml object to get at its attributes       
   
$o = simplexml_load_string($form['actions']['cancel']['#value']);

   
// replace the link with a new button
    // NOTE: jQuery is added afterwards to convert the button type from a submit to a button       
   
$form['actions']['cancel'] = array(
     
'#type' => 'button',
     
'#value' => 'Cancel',
     
'#attributes' => array(
       
'onClick' => "window.location = '" . urldecode($o['href']) . "';",
      ),
     
'#suffix' => "
        <script type='text/javascript'>
          $(document).ready(function(){
            $('form#node-delete-confirm input#edit-cancel').attr('type', 'button');
          });
        </script>"
   
);
  }
}
?>

Syndicate content