2 Replies Latest reply on Oct 15, 2008 2:34 PM by fober1

    Is it possible to call CF functions dymanically?

    Homestar9 Level 1
      Is it possible to call a ColdFusion function dynamically? For example you might have a date variable: myDate that you want to apply a ColdFusion date function to. However, the function itself needs to be dynamic because you might want to call "dateFormat", "timeFormat", "dateAdd", etc.

      Is there a way to evaluate an expression like this?

      <!-- defined the function to call and encapsulate the dynamic variable name with brackets -->
      <cfset functionToCall = "DateFormat([myVariable],'MM/DD/YYYY')">
      <cfset myDate = CreateODBCDate('03/19/1977')>

      <!-- now replace the bracketed name with the actual variable data (myDate) -->
      <cfset fullString = ReplaceNoCase(functionToCall,'[myVariable]','#myDate#','ALL')>

      <!-- display the output -->
      #evaluate(fullString )#

      What I get here is an error message because there are invalid characters in "fullString". When I simply cfoutput fullString the text it produces looks perfect, its just that I need to find a way to evaluate it.

      Any ideas?

      Thanks for taking the time to help.
        • 1. Re: Is it possible to call CF functions dymanically?
          Level 7
          presumably, which function you need to use depends on some condition...
          so you can just use a <cfif> or <cfswitch> block to check the condition
          and use appropriate function...

          you can even encapsulate it into your own function that uses built-in cf
          functions depending on some other argument passed.
          <cffunction name="myveryowndatefunction">
          <cfargument name="mydate" required="yes">
          <cfargument name='myotherargument" required="yes">
          <cfif arguments.myotherargument eq something>
          <cfreturn use_one_cf_function>
          <cfelseif ...>
          <cfreturn use_other_cf_function
          <cfreturn use_yet_another_cf_function>

          Azadi Saryev
          • 2. Re: Is it possible to call CF functions dymanically?
            fober1 Level 1

            You need to feed something to evaluate that is executable, so you should include something like "x= {dynamic stuff}" with "x' being a variable.


            <cfset myDate = "2008-10-15 14:21:37">

            <cfset functionToCallS = "DateFormat([myVariable],'MM/DD/YY')">
            <cfset functionToCallL = "DateFormat([myVariable],'MMM/DD/YYYY/HH:mm')">

            <cfset targetvar = "shortdate">
            <cfset x= evaluate("#targetvar# =" & ReplaceNoCase(functionToCallS,"[myVariable]","'#myDate#'","ALL")) >

            <cfset targetvar = "longdate">
            <cfset x= evaluate("#targetvar# =" & ReplaceNoCase(functionToCallL,"[myVariable]","'#myDate#'","ALL")) >

            VAR1(): #shortdate#<br>
            VAR2(): #longdate#<br>