Our Blog

This is a simple example where an alert box is displayed to the user before performing a critical operation. It is sometimes necessary to have a confirmation from the user, so we'll use an alert to do it. If the user clicks on "Yes", we continue, otherwise, we cancel.

Here is the code

<cfsavecontent variable="showAlert">
   var myClickHandler = function (evt){
      if (evt.detail == mx.controls.Alert.OK){
         alert("Records deleted","Completed");
      }
   }
   alert("Are you sure you want to remove all records?", "Warning", mx.controls.Alert.OK | mx.controls.Alert.CANCEL, myClickHandler);
</cfsavecontent>

<cfform name="myform" height="200" width="400" format="Flash">
   <cfformgroup type="hbox">
      <cfinput type="Button" name="myBtn" onClick="#showAlert#" value="Show Alert" />          
   </cfformgroup>
</cfform>

Note that the function alert() returns true as soon as the alert is triggered. It doesn't wait for the user response. That means we cannot do if(alert("")){ do something } else {cancel} because it will always go to "do something" regardless of what the user responds. That is why we need to make the event handler function that receives the actual response.

View live example
Download source

Nahuel Foronda

Nahuel Foronda

56 Comments

  1. Nahuel
    It's funny, it does nothing! I used it before but then I change my mind, and forgot to remove it.
    Thanks for letting me know.
    I removed it now.
  2. Felipe
    how do i submit the form insted of showin another alert after the user clix in OK?
  3. Mike
    Is there documentation on the mx.controls events you use in this? I ask because I have a problem I can't solve:

    http://www.macromedia.com/cfusion/webforums/forum/messageview.cfm?catid=22&amp;threadid=1003238&amp;enterthread=y

    I'm at a complete loss when guessing how to total up a cfgrid column. I think if I could find some documentation on the mx.controls, maybe there would be something in there that could help.

    This code snippet you wrote tonite will be very helpful in my current project, thanks again for sharing with us.
  4. Steve Walker
    Out of curiosity, is there a way to format the Alert box (e.g. height, width, etc)? I have a demo app that fills the alert box dynamically with a definition, but it is random in its layout. (www.berkeley-county.com/dcodes)
  5. This does not work with anything but an alert. I can not even do a grid.dataProvider.removeAll() inside of the function. Is there anyway around this?
  6. Nahuel
    Hi Brian,
    You can do whatever you want.
    I believe that you have a scope problem, make sure that you have a reference to your grid inside the function.
    Sample code

    &lt;cfsavecontent variable=&quot;showAlert&quot;&gt;
    // here we create a local reference to our grid.
       var myGrid = myGrid;
       var myClickHandler = function (evt)
       {
    if (evt.detail == mx.controls.Alert.OK)
    {
    alert(&quot;Records deleted&quot;,&quot;Completed&quot;);
    myGrid.removeAll()
    }
       }
       alert(&quot;Are you sure you want to remove all records?&quot;, &quot;Warning&quot;,
       mx.controls.Alert.OK | mx.controls.Alert.CANCEL, myClickHandler);
    &lt;/cfsavecontent&gt;
  7. Sven Delporte
    Hi, i want to use this code in a cfc component
    but everytime i want to run it it gives me errors. How do you use this code in a cfc component. i do it like this but doesn't work.

    cfc component code
    &lt;cfcomponent displayname=&quot;Cancel Button&quot;&gt;

    &lt;cffunction name=&quot;CancelBut&quot; output=&quot;yes&quot; access=&quot;remote&quot;&gt;
    &lt;cfsavecontent variable=&quot;showAlert&quot;&gt;
       
        var myClickHandler = function (evt){
    if (evt.detail == mx.controls.Alert.OK){
    alert(&quot;Records deleted&quot;,&quot;Completed&quot;);
    }
    }
    alert(&quot;Are you sure you want to remove all records?&quot;, &quot;Warning&quot;, mx.controls.Alert.OK |
    mx.controls.Alert.CANCEL, myClickHandler);
    &lt;/cfsavecontent&gt;
       &lt;cfreturn showAlert&gt;
    &lt;/cffunction&gt;

    &lt;/cfcomponent&gt;

    and in my form page i do an onclick like this

    &lt;cfinput type=&quot;button&quot; name=&quot;reset&quot; value=&quot; Cancel Trip &quot; onclick=&quot;getURL('cancel.cfc?method=CancelBut')&quot;&gt;

    but my component doesn't execute my actionscript code. what am i doing wrong here do i need to add something so that my actionscript code executes
  8. Sven Delporte
    if that isn't possible how do you do the acutal delete whitout going to a next page.
    i tried entering a query before the
    alert(&quot;records deleted&quot;, &quot;completed&quot;);
    but then when i load my page the records is allready deleted.

    i want to actually delete my record when i confirm with the ok button.
  9. Laura
    Sven
    The records get deleted because whatever is inside &lt;cfsavecontent&gt; will get executed, and its output saved in a variable that you can use later. What you put inside the cfsavecontent tag should be only actionscript (or cf generated actionscript).
    In order to delete the records when you click the button, you must either submit the form and do it the action page or use the custom tag described at http://www.asfusion.com/blog/entry/calling-a-cfc-from-flash-form-part2

    Hope that helps
  10. Sven Delporte
    Laura,

    I will go for the custom tag i think.
    i found this code on the macromedia forum page but this doesn't work i think i tried it and my alert box comes out but doesn't wait at any input from the user until it goes to my cfc.

    in the onclick statement of a button.
    onclick=&quot;if(alert('Are you sure','WARNING',YES|NO) == YES){getURL('components/cancel.cfc?method=CancelBut')}&quot;&gt;

    Thanks for the reply and for the help

    greets Sven
  11. Laura
    Sven,
    Yes, the code you show does not work because the return of alert is always true. You need to implement an event handler function like the one we show in the post.
  12. Laura
    Steve,
    Yes, there are ways to format the alert. I am preparing an extended example, so stay tuned!
  13. Sergey

    Sergey

    Nahuel,

    submitForm() does not work inside function. Any help?
  14. Sergey

    Sergey

    Never mind. Just have found solution in other comments. Thanks Laura.
  15. brannon

    brannon

    i cant seem to get the submitForm() to work...
    what am i missing...
  16. Ryan Guill
    How can I return a boolean value from a savecontent?

    &lt;cfselect name=&quot;mySelect&quot;...enabled=&quot;#mySelectCheck#&quot;...

    &lt;cfsavecontent variable=&quot;#mySelectCheck#&quot;&gt;
    if (myRadioButton.selectedData == 'foo'{
    return True;
    }
    else{
    return False;
    }

    this obviously doesnt work, what am I doing wrong?
    &lt;/cfsavecontent&gt;
  17. Rich F

    Rich F

    Interesting; if you add the word “delete” into the alert you get a illegal use of actionscript. I didn’t realize that the reserved words also include text in an alert{}. That goes for these words also.

    {import, new, delete, createChild, loadmovie, duplicateMovieClip, AttachMovie, registerclass, createTextField, __proto__, uiobjectdescriptor, createclassobject, createemptyobject, createchildatdepth, createchildren, createclasschildatdepth, createobject, createchild, webservice, httpservice, remoteobject}
  18. Laura
    Rich,
    Yes, that is correct. The same goes for tooltips. Not very elegant, but you can go around that by concatenating the string:
    alert(&quot;del&quot; + &quot;ete&quot;);
  19. Fritz Dimmel
    Hi Laura!
    I tried to use your example but it won't work.
    When I use your live example, everything's fine, but using the source code you provide (I also downloaded it) doesn't work.
    I use CFMX 7.0.1. Perhaps something got different in this version?
    Do you know something about this?

    Thanks,
    Fritz
  20. Christina

    Christina

    Hi, I keep getting this error:

    Errors, warnings or exceptions were found when compiling /fss/sandboxes/cblue/cfform/alert.cfm. Visit the online Flex documentation or API reference for further information.
    1 Error found.
    Error H:\fssdev\sandboxes\cblue\cfform\aler.mxml:137
    ';' expected


    I tried incorporating it into a page that I had and was getting the error and thought it must be in my code somewhere. After messing with it for a while I finally just downloaded the code and saved it and ran it by itself. This is the error I'm getting (when viewing alert.cfm in IE).

    This is without the updater.

    I ran it on another virtual that has the updater installed and it doesn't show anything at all. I added a word (&quot;aargh&quot;) in before the code and it flashes at the top of the window, then appears a little way down the page.

    Wierd?

    Thanks for your help!,
    Christina


  21. Michael White
    back on Jan 2, 2006 you replied regarding the delete keyword and you made a reference to &quot;tooltips&quot;. I would like an &quot;alert&quot; or tooltip that displays when you mouseover or hover over a button, before you click it. is there an event for that? I didn't see anything for flash forms in coldfusion.
  22. Oscar Arevalo
    About the reserved keywords, you can get around that limitation by having your actionscript code in an external file and then using an #include. If you do that, CF doesn't complain at all. I've only tried it with the &quot;new&quot; and &quot;delete&quot; strings, and I don't know if this workaround extends to actually using those strings as actual instructions.
  23. Chad
    I am currently working on a very large RIA for an admin tool that will manage 3 large websites. I am using flash forms almost exclusivesly. I have a simple form validation that just tells me in an alert if the field has info in it. I would like to incorporate the built in flash form validation, but it seems that I can't "detect" if the submit button has been "rejected" or "accepted" based on the results of the form validation.

    When the button is simply:
    <cfinput type="button" name="btn_addNewAct" enabled="no" value="Save" onclick="addNewAct()" src="images/nav/check.jpg">

    When I change it to:
    <cfinput type="submit" name="btn_addNewAct" enabled="no" value="Save" onclick="addNewAct()" src="images/nav/check.jpg">

    then the built in form validation from cf works...but the addNewAct() function still fires. Do we have access to know if the validation failed or not.

    Thanks,
  24. Kieren
    Hey There!
    How do I get it to set a form field value when the "OK" button is clicked? Thanks! Kieren
  25. Dexter
    One more thing to note. If your would like to only delete a single row (e.g. selected item from a grid), you can transfer the same code above into a <cfformitem type="script"> function and it will work just like javascript. You can pass arguments to code block such as an ID or confirm with the name of the item to be deleted.

    JG4
  26. Erik
    For some reason, flash remoting inside of the callback function for the confirmation dialogue when OK is clicked does not work. No errors, just sits there.
  27. Laura
    Chad,
    You need to use a button (not a type "submit") and then trigger the submit manually if they clicked ok. Use _root.submitForm()

    Kieren,
    First put your controls in scope (suppose myControl is a text input) and then set it.
    var myControl = myControl;
    var myClickHandler = function (evt){
    if (evt.detail == mx.controls.Alert.OK){
    alert("Records deleted","Completed");
    myControl.text = "I am changed!";
    }
    }


    Erik,
    That is due to scope issues. Make sure you put your controls into scope. (even if your remoting service is stored in a form variable such as myForm.myService) as in:
    var myForm = myForm;
    var myControl = myControl;
    //do the other stuff, show the alert, etc
  28. Tony Eckert

    Tony Eckert

    I enjoyed the real estate application, and based my inventory app on the techniques used. I would also like to add an alert box to confirm a deletion of an inventory item so as to bullet-proof a wrongly deleted item. I cannot figure out how to implement this alert box code into my app though. Could you post a solution to adding the alert box to the real estate app? That would give me some insight to my problem.
  29. eatmorepossum

    eatmorepossum

    I am trying to call a function from my cfform. Is this possible? It seems to call the function as soon as the variables declared.

    <cfsavecontent variable="showAlert">
    var myFunction = updatedownloaddate();   
    var myClickHandler = function (evt){
    if (evt.detail == mx.controls.Alert.OK){
           
           myFunction;
    }
    }
    alert("If you agree stuff will happen.", "Warning", mx.controls.Alert.OK | mx.controls.Alert.CANCEL, myClickHandler);
    </cfsavecontent>
  30. thomary

    thomary

    I have a flash cfform working but I have an error checker on the action page with a back button. But the form reloads with no data. I found that you should use timeout=some number of seconds. I have this set to 600 and still the flash form reloads with no data.

    I have tried both:
    <p><a href="javascript:history.back();">Return</a></p>
    On a button used: onclick="if (history.length > 0){history.back()}"

    Both go back to the form as a new page not back to the page with data.

    I'm now looking into the alert but it seems to be used in conjunction with "validate". The error checks have queries and will not work with validate. Can someone help me with some (hopefully simple) code Like:
    <cfif form.fieldname eq "">
    do alert message="You must select fieldname
    </cfif>
  31. Laura
    Tony,
    Yeah, the real estate app doesn't confirm with the user when deleting items. You can check the file explorer on the submitRemoveFile() function where you will see how to do it.

    eatmorepossum,
    Your syntax is mostly correct, but you are not calling the function within the alert, you need to add the parenthesis myFunction(); and remove them from the var declaration var var myFunction = updatedownloaddate;

    thomary,
    If what you want is to preserve what the user entered, the back button will never work, because the only data that a flash form loads is the data you set by using ## in the fields, or queries, etc. What I would do is not have the action page be different and let them use the back button but rather repopulate the form with the data they entered if the error checking does not go through. You could use onload to show an alert there if you want, but make sure you are not using cfoutput in ActionScript because otherwise your form will recompile each time (use a hidden field for the alert message instead).
  32. Glandry

    Glandry

    Anyone know if there is a "prompt" function like the "alert" function in CF. I wrapped some javascript in a cfscript tag but it wont recognize "prompt" used in javascript.
  33. Laura
    Bruce,
    You must either call a remoting service that deletes the record or submit the form and handle that in the action page.

    Glandry,
    I think you are kind of confused... first, you cannot put javascript in a cfscript tag, as it only accepts cf code (in its script form that does not use tags). Second, you cannot use javascript in a cfform format flash because it only understands ActionScript. But to answer your question, no, there is no "prompt" in flash forms.
  34. dan
    Does #include work with cfforms as a work around reserved keywords like Oscar Arevalo says?
  35. Sam
    I want to use the alert function and have change the button that trigger the fuction to Button type instead of submit.

    But I don't know how to add into the function to get the form to submit and get the records deleted.(see code below)

    <cfsavecontent variable="showAlert">
       var myObj = {};
        var myClickHandler = function (evt){
    if (evt.detail == mx.controls.Alert.OK){

       How to get the form to submit and tell the user that the records is deleted;            
    }
    }

    alert("Are you sure you want to remove all records?", "Warning", mx.controls.Alert.OK |
    mx.controls.Alert.CANCEL, myClickHandler);
    </cfsavecontent>
  36. Laura
    dan,
    We used #include in the MXNA reader (before we had cfformitem type="script") to separate the files to make it easier to work with. At that time, using #include didn't have any advantage other than that (I checked using new, etc). I never checked again, as I was not interested in finding more hacks for cfforms that can be easily changed by Adobe in the future. It seems though, that when some of the updaters got applied, this changed, and the code in the included .as files is not checked for "illegal" keywords and "new" works.
    So the answer is yes, it can be used as a workaround, but I wouldn't use it, since it might very possibly be limited in the future and you don't want your code to break when a new version of CF gets installed.
  37. Anang
    Is it possible to get a "prompt" dialog in "as" just like a javascript prompt dialog ?
  38. Paula
    I do not have Coldfusion MX 7.0.1. I have an earlier version (not MX).

    I need to use a confirm box and then do a template include or refresh the current page.

    Is this possible?
  39. Tim
    Is there any way you can call this alert method without using a cfinput like in the example above? For example I would like to call the alert box when a form is submitted.

    Thanks
    Tim
  40. Patrick

    Patrick

    I know this article is a couple of years old, but I'm hoping someone might still have a bit of insight for me. I need to display an alert based on a variable set by a javascript. Because of asynchronous processing of actionscript (I think), I can't get it to work. Here is a code sample:

    <script language="JavaScript" type="text/javascript">
    function setMyAlert()
    {
    var x = "Yes1234";
    window.document.myForm.SetVariable("myField.text", x);
    };
    </script>

    <cfsaveContent variable="getHashjs">
    getURL("javascript:setMyAlert()");
    alert(myField.text);
    </cfsavecontent>


    I even tried to set a small delay (below) to help, but it did not work.

    <cfsaveContent variable="getHashjs">
    for (var x:Number = 0; x < 100; x++)
    {
    if (x==0){getURL("javascript:setMyAlert()");};
    if (x==99) {
    alert(myField.text);};
    };
    </cfsavecontent>


    Does anyone have any suggestions?

    Thanks,
    Patrick
  41. Todd
    I have the following, but the form is not getting submitted.
    Can someone help?
    Thanks
    <cfsavecontent variable="showAlert">
    var myClickHandler = function (evt){
    if (evt.detail == mx.controls.Alert.OK)
        {
    _root.submitForm();
    }
    }
    alert("Record Updated", "Warning", mx.controls.Alert.OK, myClickHandler);
    </cfsavecontent>
  42. Jason
    [quote]
    Bruce,
    You must either call a remoting service that deletes the record or submit the form and handle that in the action page. [/quote]

    Bruce was asking how to execute the delete query. I'm having the same problem.

    <cfinput type="button" name="deleteJob" value="DELETE" onClick="#showAlert#">

    I submit the form back to the same page and check to see if FORM.deleteJob is defined..

    <code>
    <cfif IsDefined("FORM.deleteJob")>
    <cfquery.....>
    DELETE FROM foo
    WHERE ID = #FORM.ID#
    </cfquery>
    </cfif>
    </cold>

    Unfortunately, it appears that this handy script doesn't pass FORM.deleteJob from the delete button.
  43. Jason
    Oops :)

    <cfif IsDefined("FORM.deleteJob")>
    <cfquery.....>
    DELETE FROM foo
    WHERE ID = #FORM.ID#
    </cfquery>
    </cfif>
  44. MaxD
    Laura: Great post.

    I too, however, experienced the problem with passing a FORM.deleteItem value with the _root.submitForm() solution. I came up with a workaround. I'm sure it's not the most elegant solution, but it works for me, and might for others (Jason?):

    <!--- HANDLE DELETE REQUESTS --->

    <cfsavecontent variable="showDeleteAlert">
    var DeleteMe = editform.editid.value;
    var myClickHandler = function (evt){
    if (evt.detail == mx.controls.Alert.OK){
    <cfoutput>_root.getURL('index.cfm?page=#Page#&deleteid=#editquery.id#')</cfoutput>
    }
    }
    alert("Are you sure you want to remove this record?", "Warning", mx.controls.Alert.OK | mx.controls.Alert.CANCEL, myClickHandler);
    </cfsavecontent>

    Obviously, this solution ONLY works for the scenario Jason described, in which no form values actually have to be passed, but merely the id of the item to be deleted. And it only works if we can send that value in the query string. Perhaps Laura could refresh this post with a more sophisticated/actionscript solution.

    Thanks again!
    max
  45. MaxD
    Oh. One more thing. My solution assumes some variables established (Page and editquery.id). I also found wrapping the script in a cffunction allowed me to pass arguments to it, like so:
    <cffunction name="confirmDelete" output="false" returnType="string">
    <cfargument name="Arg1" type="string" required="true" hint="Arg1 hint">
    <cfargument name="Arg2" type="string" required="true" hint="Arg2 hint">

       <cfsavecontent variable="showDeleteAlert">
        var DeleteMe = editform.editid.value;
        var myClickHandler = function (evt){
        if (evt.detail == mx.controls.Alert.OK){
        <cfoutput>_root.getURL('index.cfm?page=#arguments.Arg1#&deleteid=#arguments.Arg2#')</cfoutput>
        }
        }
        alert("Are you sure you want to remove this record?", "Warning", mx.controls.Alert.OK | mx.controls.Alert.CANCEL, myClickHandler);
       </cfsavecontent>
       <cfreturn showDeleteAlert>
    </cffunction>


    Then, you can call it, like so:
    <cfinput type="Button" name="deleteIt" onClick="#confirmDelete(Page,editquery.id)#" value="Delete Record" />

    This might provide some more flexibility. Who knows?
  46. MaxD
    one final thought: You can ignore the "var DeleteMe = editform.editid.value;" within the cfsavecontent. It is vestigial code from when I was trying to get this working!
  47. Jason
    Thanks for the input Max. I appreciate you taking the time to help.

    I've done my best to keep URL variables to a minimum. Typically, I only use them to pull data from the DB. I'm not sure I want to write data to the DB (or delete) even when using <cfqueryparam cfsqltype="foo" value="#bar#"> for protection.

    For the Actionscripters... could I use LoadVars to grab a hidden field from my form and send it back to the same page?

          var myClickHandler = function (evt)
          {
             if (evt.detail == mx.controls.Alert.YES)
             {      
                   myFormContent = new LoadVars();
                   myFormContent.myHiddenField = "deleteMe";
                   
                   myFormContent.send("index.cfm, "" , "post");
             }
          }


    Is that any 'safer' then using the URL query string? TIA!
  48. Jason
    Oops... guess not.

    var myClickHandler = function (evt)
          {
             if (evt.detail == mx.controls.Alert.YES)
             {      
                   var myFormContent:LoadVars = new LoadVars();
                   
                   myFormContent.field1 = field1.text;
                   myFormContent.field2 = field2.text;
                   myFormContent.field3 = field3.text;
                   
                   myFormContent.send("index.cfm, "post");
             }
          }


    Resulted in:

    The following information is meant for the website developer for debugging purposes.
    Error Occurred While Processing Request
    Illegal usage of actionscript org.apache.oro.text.regex.Perl5Pattern@1075e59.
    The following actionscript commands are not allowed: "import, new, delete, createChild, loadmovie, duplicateMovieClip, AttachMovie, registerclass, createTextField, __proto__, uiobjectdescriptor, createclassobject, createemptyobject, createchildatdepth, createchildren, createclasschildatdepth, createobject, createchild, webservice, httpservice, remoteobject".
  49. Jason
    Interesting... "upgraded" to CF8 and now I can use the LoadVars object. That means I'm going to have to put each of the CF form vars into that object otherwise they are lost.