Thursday, March 19, 2009

CF: ColdFusion functions and the case of the mysterious space

Spent lots of time trying to find out why a space was returned from a function call to a function in a component. We would place the output directly into a html form text control, but a space would always be added to the front of the expected return string.
Broke out the old Hex editor to save and check file contents. Output each character at a time, just could not see why this would happen.
Many hours later, a headache started to kick in. Time for a break. Then, a hunch started knocking at the back of my scull and got louder and louder.
To prove it to myself, I created an intermediate variable into which I stored the function result. When this scheme was used, no space. If I used the function output in place, space! It turned out to be the Output attribute of the function definition. You will need to set it to 'No'. If you leave it off and attempt to use the function in place, Coldfusion will introduce a space in the return. Very, very annoying.

Here is sample code to reproduce the problem, two function that are identical except one has the output attribute specified; if you use the function 2 inline CF will produce a space in front of the output; see the output for f2 below:


<cffunction name="fFunction1" output="No">

<cfset var strReturn ="Hello World">
<cfreturn strReturn>
</cffunction>

<cffunction name="fFunction2" >
<cfset var strReturn ="Hello World">
<cfreturn strReturn>
</cffunction>

<cfset sOutput1=fFunction1()>
<cfset sOutput2=fFunction2()>

<cfoutput>
f1:--#fFunction1()#--
<BR>
o1:--#sOutput1#--
<BR>
f2:--#fFunction2()#--
<BR>
o2:--#sOutput2#--
<BR>
</cfoutput>

Output:

f1:--Hello World--
o1:--Hello World--
f2:-- Hello World--
o2:--Hello World--

4 comments:

Will said...

You are an absolute lifesaver!!!!

I have had this problem for ages, and just assumed there was no solution, so I have coded arounded this so many times.

Thank you so much for this solution!

Worked like a charm!

khosi said...

wow thanks a lot!

Marty McGee said...

BonCode - I read your suggestion to add the cffunction parameter output="false" to rid my mysterious single space in front of my function response string -- Trim() didn't help until I deliberately set a variable to hold the response of my cffunction string function. Once I through in the missing parameter output="false", my cffunction (local udf, really) worked. Thanks again, BonCode.

JF said...

Cheers!

We've been having this issue randomly for such a long time, finally decided that enough was enough and I found this post.

The funny thing is that it doesn't always happen.