Hey guys,

How is it possible to create simple confirmation popup dialog boxes?! jQuery, javascript ... etc, anything!

I've searched a lot but found tons of non-working suggestions and code.

Please help!

Thanks for your time and help :)

Comments

bboldi’s picture

Well, I don't know what have you tried and what do you need exactly... jQuery is a pretty reliable script, and has nice features - plugins but if you want to simply confirm form submission - for example - javascript is more than enough. A bit more info about what do you want to accomplish would help a little ;)

bboldi’s picture

Here is a simple example of javascript confirmation implementation for form API submit button:

  $form['actions']['delete'] = array(
    '#type' => 'button',
    '#value' => t('Delete'),
    '#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}')
  );

this will submit the form only after user click OK on javascript confirmation dialog.

Hope it helps!

devoted.designer’s picture

THANK YOU MAN!!!!!!!!!!!!

YOUR A LIFE SAVER .... i don't believe how went off my mind ;)

Thanks again.

devoted.designer’s picture

The code you gave me worked like a charm, but i was wondering:

If i wish to use a jQuery plugin instead ... how is that possible?

I'm using a jQuery plugin called "Apprise", but don't seem to know how to get it to work!

I tried the following code in my form:

drupal_add_css(drupal_get_path('module', 'participate') .'/css/apprise.min.css');
drupal_add_js(drupal_get_path('module', 'participate') .'/js/apprise-1.5.min.js');
	
$form['accept'] = array(
    '#type' => 'submit',
    '#value' => t("Accept"),
    '#attributes' => array(
        'onclick' => '(function($){$(
            function() {apprise("Ready to begin?", {"verify":true}, function(r){ if(!r){return false;}})}
            )})(jQuery);'
        ),
	'#submit' => array('accept_form'),
);

The apprise function is correctly implemented ... (I double checked).

Am I adding the jQuery plugin correctly?

Is this the right place to add the .js and .css?! (To insure that these js and css are only loaded once with the loading of the website)

How can i correctly implement the jQuery code in the attribute?

Sorry for asking too much, I'm a newbie :(

Thanks for your time and help

bboldi’s picture

Ok, there is a few problems with this code.

1st, the current Apprise module is not compatible with Drupal 7's jquery implementation because it uses $. so 1st of all what you need to do is download the non minimized version of the plugin and replace all the $ characters with "jQuery". Here is the modified version:

// Apprise 1.5 by Daniel Raftery
// http://thrivingkings.com/apprise
//
// Button text added by Adam Bezulski
//

function apprise(string, args, callback)
	{
	var default_args =
		{
		'confirm'		:	false, 		// Ok and Cancel buttons
		'verify'		:	false,		// Yes and No buttons
		'input'			:	false, 		// Text input (can be true or string for default text)
		'animate'		:	false,		// Groovy animation (can true or number, default is 400)
		'textOk'		:	'Ok',		// Ok button default text
		'textCancel'	:	'Cancel',	// Cancel button default text
		'textYes'		:	'Yes',		// Yes button default text
		'textNo'		:	'No'		// No button default text
		}
	
	if(args) 
		{
		for(var index in default_args) 
			{ if(typeof args[index] == "undefined") args[index] = default_args[index]; } 
		}
	
	var aHeight = jQuery(document).height();
	var aWidth = jQuery(document).width();
	jQuery('body').append('<div class="appriseOverlay" id="aOverlay"></div>');
	jQuery('.appriseOverlay').css('height', aHeight).css('width', aWidth).fadeIn(100);
	jQuery('body').append('<div class="appriseOuter"></div>');
	jQuery('.appriseOuter').append('<div class="appriseInner"></div>');
	jQuery('.appriseInner').append(string);
    jQuery('.appriseOuter').css("left", ( jQuery(window).width() - jQuery('.appriseOuter').width() ) / 2+jQuery(window).scrollLeft() + "px");
    
    if(args)
		{
		if(args['animate'])
			{ 
			var aniSpeed = args['animate'];
			if(isNaN(aniSpeed)) { aniSpeed = 400; }
			jQuery('.appriseOuter').css('top', '-200px').show().animate({top:"100px"}, aniSpeed);
			}
		else
			{ jQuery('.appriseOuter').css('top', '100px').fadeIn(200); }
		}
	else
		{ jQuery('.appriseOuter').css('top', '100px').fadeIn(200); }
    
    if(args)
    	{
    	if(args['input'])
    		{
    		if(typeof(args['input'])=='string')
    			{
    			jQuery('.appriseInner').append('<div class="aInput"><input type="text" class="aTextbox" t="aTextbox" value="'+args['input']+'" /></div>');
    			}
    		else
    			{
				jQuery('.appriseInner').append('<div class="aInput"><input type="text" class="aTextbox" t="aTextbox" /></div>');
				}
			jQuery('.aTextbox').focus();
    		}
    	}
    
    jQuery('.appriseInner').append('<div class="aButtons"></div>');
    if(args)
    	{
		if(args['confirm'] || args['input'])
			{ 
			jQuery('.aButtons').append('<button value="ok">'+args['textOk']+'</button>');
			jQuery('.aButtons').append('<button value="cancel">'+args['textCancel']+'</button>'); 
			}
		else if(args['verify'])
			{
			jQuery('.aButtons').append('<button value="ok">'+args['textYes']+'</button>');
			jQuery('.aButtons').append('<button value="cancel">'+args['textNo']+'</button>');
			}
		else
			{ jQuery('.aButtons').append('<button value="ok">'+args['textOk']+'</button>'); }
		}
    else
    	{ jQuery('.aButtons').append('<button value="ok">Ok</button>'); }
	
	jQuery(document).keydown(function(e) 
		{
		if(jQuery('.appriseOverlay').is(':visible'))
			{
			if(e.keyCode == 13) 
				{ jQuery('.aButtons > button[value="ok"]').click(); }
			if(e.keyCode == 27) 
				{ jQuery('.aButtons > button[value="cancel"]').click(); }
			}
		});
	
	var aText = jQuery('.aTextbox').val();
	if(!aText) { aText = false; }
	jQuery('.aTextbox').keyup(function()
    	{ aText = jQuery(this).val(); });
   
    jQuery('.aButtons > button').click(function()
    	{
    	jQuery('.appriseOverlay').remove();
		jQuery('.appriseOuter').remove();
    	if(callback)
    		{
			var wButton = jQuery(this).attr("value");
			if(wButton=='ok')
				{ 
				if(args)
					{
					if(args['input'])
						{ callback(aText); }
					else
						{ callback(true); }
					}
				else
					{ callback(true); }
				}
			else if(wButton=='cancel')
				{ callback(false); }
			}
		});
	} 

then here is an example for the proper implementation:


function b2test_form1()
{
    drupal_add_css(drupal_get_path('module', 'b2test') .'/css/apprise.css');
    drupal_add_js(drupal_get_path('module', 'b2test') .'/js/apprise-1.5.full.js');    
    
    drupal_add_js('
    
        function confirmation()
        {
              apprise("Are you sure?", {"verify":true}, function(r)
                {
                if(r)
                    { 
                        jQuery("#b2test-form1").submit();                        
                    }
                });
        }

    ',array( 'type' => 'inline'));
    
  $form['actions'] = array('#type' => 'actions');
  
  $form['actions']['text'] = array(
    '#type' => 'item',
    '#markup' => 'Delete?'
  );
  
  $form['actions']['delete'] = array(
    '#type' => 'button',
    '#value' => t('Delete'),
    '#attributes' => array('onclick' => 'confirmation();return false;')
  );
  
  return $form;        
}

make sure to change jQuery("#b2test-form1").submit(); to your form's id (it's your form function name, just replave _ to -).

Another tip:

To see if you have included everything correctly, or basically for jQuery debug either use Chrome's built in debugging functionality, or Firefox with Firebug plugin ;)

Hope this helps.

devoted.designer’s picture

I take my hat off to you!

Thank you so much for your time and invaluable help.

TOTAL RESPECT :)

I still have a tiny question:
You used the default form submit, what if I wanted to call a custom-named function?
That is, in case I have 2 submit buttons, each with it's own submit array!?
such as:

function myform($form, $form_state) {

    ...

    $form['save'] = array(
        '#type' => 'submit',
        '#value' => t("Save"),
        '#submit' => array('save'),
        '#attributes' => array('onclick' => 'apprise("Are you sure?", {"verify":true}, function(r)
                {
                if(r)
                    {
						jQuery("#myform").submit();
                    }
                });return false;'),
    );
    $form['delete'] = array(
        '#type' => 'submit',
        '#value' => t("Delete"),
        '#submit' => array('delete'),
        '#attributes' => array('onclick' => 'apprise("Are you sure?", {"verify":true}, function(r)
                {
                if(r)
                    {
						jQuery("#myform").submit();
                    }
                });return false;'),
    );

    return $form;
}

function save($form, $form_state) {
    ...
}
function delete($form, $form_state) {
    ...
}

What should i replace jQuery("#myform").submit(); with?

bboldi’s picture

Well, You can always define a hidden element in your form, and set its value to something to verify which button was pressed, and do different action based on that value. for example: instead of

jQuery("#myform").submit();

you add a hidden field:


$form['myhiddenvaluefield'] = array(
    '#type' => 'hidden',
    '#value' => ''
);

then add a javascript code

jQuery("#edit-myhiddenvaluefield").val('save');
jQuery("#myform").submit();

or

jQuery("#edit-myhiddenvaluefield").val('delete');
jQuery("#myform").submit();

and in yourform_submit(... function just do different things for $form['values']['myhiddenvaluefield']=='delete' ... you get the idea.

devoted.designer’s picture

Hidden fields got no id!!! (I checked that via firebug)

That's why i can't seem to be able to select that field to change it's value!

I replaced the hidden field with a text field, selected it using the jQuery function (you gave me) and changed its value perfectly.

But a textfield can't be used here! A hidden one must be used ....

I also tried to select it (hidden field) using jQuery selectors ... but no luck:
jQuery("input[name="myhiddenvaluefield"]").val("save");

Any Ideas ?

bboldi’s picture

You can add an id like this:

  $form['actions']['hiddenitem'] = array(
    '#type' => 'hidden',
    '#value' => '',
    '#attributes' => array('id' => 'yourid')
  );

it will result:

<input id="yourid" type="hidden" name="hiddenitem" value="" /> 
devoted.designer’s picture

I don't know why such simple solutions didn't come to my mind?!

Honestly ... I don't know what to say :)

Thank you so much for your time and help ...

bboldi’s picture

You are welcome!

larssin’s picture

Thanks :)
I've been looking for a solution to this for some time. I had the idea at some point, that I could maybe do this, but according to the FAPI '#attributes' is not supported for hidden fields: http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.... . How can that be?

sidrasultana’s picture

Thanks, it works fine for me

manmohandream’s picture

Hello,
i hope this code will work for me, But pls let me know the steps to use this code.
thanks

queryblitz’s picture

How could I get this to work on a node Save button? And where does this code go?

syedsana’s picture

Hi
I have used your suggestion it worked fine thank alot. But today got stuck in some awkward thing. as my senerio is I have two submit button. One Approves and other Not Approve. When I press the approve button it goes to the approve function and run it. and when i Not approve, it first confirms and when pressed OK it runs the not Approve function.
But the issue comes when I press the Not Approve button the confirmation appears I press cancel. Nothing happens. When I press the Approve Button it goes to the Not approve Submit Function. Not getting the idea why it is doing so. Please suggest any solution for it.

   $form['recommend'] = array
        (
          '#type' => 'submit',
          '#value' => t('Recommended'),
          '#submit' => array('assist_leave_request_form_submit_recommend'),
          
        );
        
        $form['not_recommend'] = array
        (
          '#type' => 'submit',
          '#value' => t('Not Recommended'),
          '#submit' => array('assist_leave_request_form_submit_notrecommend'),
          '#attributes' => array('onclick' => 'if(!confirm("Are your sure?")){return false;}'),
        );
        
function assist_leave_request_form_submit_recommend($form, &$form_state) {
      
    $request = 0;
    foreach (($form_state['values']['table']) as $key => $value) {
        if(!empty($value)){
            $comments = empty($form_state['values']['comments'][$value]) ? NULL : $form_state['values']['comments'][$value];
            $request = db_update('ifes_emp_leave_request')
                    ->fields(array(
                      'is_approved_sup' => 1, 
                      'comments_sup' => $comments,
                      'approved_sup_date' => date('Y/m/d H:i:s'),
                      ))
                     ->condition('leave_req_id',$value,'=')
            ->execute();
             request_to_mngmt($value);
                         
        }
         
        else {
            drupal_set_message("Please select the checkbox then submit!");
        }
             
        }
        
         if($request){
                drupal_set_message("The status of the leave request is updated and the email is forwarded to the Management!");
          }
          else {
                 drupal_set_message("System has some issue! Please call Web Admin.");
          }
        
        
        
    }
function assist_leave_request_form_submit_notrecommend($form, &$form_state) {
      
    $request = 0;
    foreach (($form_state['values']['table']) as $key => $value) {
       if(!empty($value)){
            $comments = empty($form_state['values']['comments'][$value]) ? NULL : $form_state['values']['comments'][$value];
            $request = db_update('ifes_emp_leave_request')
                  ->fields(array(
                    'is_approved_sup' => 0,
                    'is_approved' => 0,
                    'comments_sup' => $comments,
                    'approved_sup_date' => date('Y/m/d H:i:s'),
                    ))
                  ->condition('leave_req_id',$value,'=')
                  ->execute();

                  msg_of_notapprove($value);

         
       }
       else {
            drupal_set_message("Please select the checkbox then submit!");
       }
           
    }
     if($request){
        drupal_set_message("The leave request is not approved ");
     }
     else {
         drupal_set_message("System has some issue! Please call Web Admin.");
     }
}
sergey-shulipa’s picture

bboldi, thx a lot! Your solution is the easiest and it works!
It's important to remember that many things are form element's #attributes.
Thank you!

shyamkumawat’s picture

Thank you so much MEN.

Your are a life saver

sandstrom’s picture

Hi,

I have followed the D7 custom module creation tutorial. But I need some more information with reference codes.
I need to build up a admin controlled custom module with some text boxes, checkboxes / radiobuttons, along with image upload feature. I need to add,edit, delete those values from admin & the added values will show in the front end. Can anyone please help me with some reference codes of any type of custom module for above mentioned type.

Help will be much appreciated.

Thanks in advance...

Anonymous’s picture

Thank you very much for this code. I will try to use it for every node delete confirmation on Drupal 6 and I'll post here if it works.

EDIT //
I thought it would be easier but I guess was presomptuous :)

I tried to use apprise on this form but it doesn't work :

/**
 * The delete status confirmation form.
 */
function _facebook_status_delete(&$form_state, $status) {
  if (module_exists('modalframe')) {
    modalframe_child_js();
  }
  $form['infotext'] = array('#value' => '<p>'. t('Are you sure you want to permanently delete the status %status?', array('%status' => $status->message)) .'</p>');
  $form['confirm'] = array(
    '#type' => 'submit',
    '#value' => t('Confirm'),
    '#submit' => array('_facebook_status_delete_confirm'),
  );
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#submit' => array('_facebook_status_delete_cancel'),
  );
  $form['status-sid'] = array(
    '#type' => 'value',
    '#value' => $status->sid,
  );
  return $form;
}

/**
 * Deletes a status.
 */
function _facebook_status_delete_confirm($form, &$form_state) {
  $status = facebook_status_load($form_state['values']['status-sid']);
  facebook_status_delete_status($status);
  drupal_set_message(t('Status deleted.'));
  if ($_GET['destination']) {
    $form_state['redirect'] = $_GET['destination'];
  }
  else {
    $form_state['redirect'] = ($status->type == 'user' ? 'user' : '<front>');
  }
  if (module_exists('modalframe')) {
    modalframe_close_dialog();
  }
}

/**
 * Cancels status deletion.
 */
function _facebook_status_delete_cancel($form, &$form_state) {
  $status = facebook_status_load($form_state['values']['status-sid']);
  if ($_GET['destination']) {
    $form_state['redirect'] = $_GET['destination'];
  }
  else {
    $form_state['redirect'] = ($status->type == 'user' ? 'user' : '<front>');
  }
  if (module_exists('modalframe')) {
    modalframe_close_dialog();
  }
}

Do I also have to change the apprise code like you did for D7 ?

Thank you

bboldi’s picture

I have not tried it, but I think that you don't need to change the jQuery module for Drupal 7.

yogwiz’s picture

Thanks a lot!!!