Saturday, April 14, 2007

Passing arguments using "argumentCollection"

There is a much flexible way to pass arguments to a function: passing the arguments struct to the function as "argumentCollection".
For example:

<cfscript>
  args = StructNew();
  args.field1="some text";
  args.field2="true";
  args.field3=99;
  myFunction(argumentCollection=args);
</cfscript>

The code is much cleaner and readable using this method. Especially when a function has many arguments and some of them are optional. Another advantage is that if a function mainly deal with data passed from a form, I can pass the whole form struct in, no need to specify them one by one.

myFunction(argumentCollection=args)

I used to invoke a function like this:

<cfset myFunction(field1="some text",field2="true",field3=99) />



But the code could get really messy when there are many arguments. Not to mention when some of the arguments are optional and passed dynamicly, I would need to use cfinvoke and put cfinvokeargument in cfif block.

<cfset myFunction(field1="some long long long long text",
                  field2="false",
                  field3=99,
                  field4=Now()) />


With the "argumentCollection" approach, I can easily pass arguments when needed:

<cfscript>
  args = StructNew();
  if (hasField1) args.field1 = "some text";
  if (hasField2) args.field2 = "true";
  if (hasField3) args.field3 = 99;
  myFunction(argumentCollection=args);
</cfscript>

Thursday, April 12, 2007

Canceling Default Tab Key Action in Form Input

As I was developing a "Google Suggest" like input box, I encountered a problem that I was not able to cancel the default tab action (which would focus on next input field) from my "onkeyup" handler. Everything in my keyUpHandler did get executed, but the input focus still jumped to the next input field. After some dumping, alerting and break-pointing I then figured out that the "jump" was actually happened at the "onkeydown" phrase. So by the time my keyUpHandler cancel the default action, the action that I was trying to prevent had already happened!!!

Wednesday, April 11, 2007

CFMAIL and NullPointerException

This morning when I tried to write a function that calls CFMAIL, I kept getting NullPointerException. Here was the code snippet:

<cfmail 
  from="#arguments.email_from#"
  failto="#arguments.email_from#"
  replyto="#arguments.email_from#"
  to="#arguments.email_to#"
  cc="#arguments.email_cc#"
  bcc="#arguments.email_bcc#"
  subject="#arguments.email_subject#"
  type="html"
  spoolenable="false">
    <div><cfoutput>#arguments.email_body#</cfoutput></div>
</cfmail>


Originally I thought it's because of empty 'email_cc' and 'email_bcc' get passed in from the FORM variables, but turns out that we don't need CFOUTPUT inside the CFMAIL tag!!!! After I took out the CFOUTPUT , everything worked just fine.

You can see this problem discussed much detailed in Raymond Camden's blog.