I am using cffile to create a new file or update an existing file, depending on what the user requested. The request comes through a form from the previous procedure, so the code involving cffile looks like this:
<cfset thefile = "#form.dyn#">
<cfoutput>
<cfsavecontent variable = "testvar">
#form.editor1#
</cfsavecontent>
<cffile action = "write"
file = "/var/www/reports/#thefile#.cfm"
output = "#testvar#">
</cfoutput>
When I am done writing to the file, I want to confirm to the user that this happened. For a new file I could use IsDefined to check that it is there. But I can't think of a way to check for an existing file that was updated. I considered a try/catch on the cffile, but the catch operates only if nothing seems to go wrong. If I don't get an error on the catch, can I assume everything is all right? I would prefer a direct check if possible. Does anyone have an idea?
If <cffile> doesn't work, it'll tell you by throwing an exception. If it doesn't do that, you can safely assume it has worked. Don't over-engineer your app.
You could use cfdirectory with the action="list" and filter="your-filename" to get the following information about the uploaded file:
If action = "list", cfdirectory returns the following result columns, which you can reference in a cfoutput tag:
name: Directory entry name. The entries "." and ".." are not returned.
directory: Directory that contains the entry.
size: Directory entry size.
type: File type: file, for a file; dir, for a directory.
dateLastModified: The date that an entry was last modified.
attributes: File attributes, if applicable.
mode: Empty column; retained for backward compatibility with ColdFusion 5 applications on UNIX.
Of interest to you is the dateLastModified column.
So you should be able to do something like:
<cfdirectory action="list" name="dirQuery" directory="C:/var/www/reports/" filter="#thefile#.cfm">
Then you can dump that result to see what information is available to you:
<cfdump var="#dirQuery#">
The dateLastModified column can be accessed like:
<cfoutput>#dirQuery.dateLastModified#</cfoutput>
Use CFDirectory to get the file's dateLastModified before you update the file and then again afterwards. If they are not the same, then it was updated.
I'm trying to create basically a library of UDFs (User Defined Functions) for a web site run in ColdFusion. While doing this I am trying to find out what the differences are between cfc and cfm files. Which would be more helpful in creating this library of functions? I know that I can use
<cfinclude template="mytemplate.cfm>
to include it in a page but that will run the entire contents of that cfm on that page every time. I don't know and easier way to use cfc other than to create an object of the cfc and call the function that way.
<cfobject type="component" action="create" name="test">
Any ideas?
The way that I do it is to create all my UDF in a cfc. I then initialize that cfc on application start:
public function onApplicationStart() {
// Application settings
application.util = createObject("component","cfc.util");
return;
}
use a cfc you can call more easily from more places, if its not too huge put it into your application scope
I'm currently learning ColdFusion. I have a background in PHP and I am a bit confused by this.
I have a select menu and I want the options to be saved in a different file. (For example options.cfm) When I call the file I want to include the options inside the select menu.
Now I realize I could probably do it with something like this:
<select>
<cfinclude template="options.cfm">
</select>
Although what I really want to do is a bit more complicated. I want to have the cfinclude saved inside a variable. I realize this won't work but it is basically what I want to accomplish:
<cfset options=<cfinclude template="options.cfm">>
Is there anyway to do that? Or at least a better way to accomplish what I am doing.
Take a look at the cfsavecontent tag, It allows you to capture what would otherwise have been output to the response :
<cfsavecontent variable="options">
<cfinclude template="options.cfm">
</cfsavecontent>
UPDATE: Instead of using cfsavecontent every time you need those options saved to a variable, you could instead do it once inside of the options.cfm file. Then, anytime you include the file, it will create the variable.
<!--- Inside options.cfm --->
<cfsavecontent variable="options">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</cfsavecontent>
Then where ever you needed that variable to exist you would simply need to cfinclude that file.
<cfinclude template="options.cfm">
i know this is a bit late but one issue i see is if this is site wide or just per client.
if site wide then great but if it is different on each client it could cause some issues.
my solution as i don't use cookies or sessions is to create a temp table and write the variables to it. each page that loads and needs that data queries and/or writes to the table.
a client id variable is created when the client visits the site and the table is named it.
just a thought.
I've get a variable that can contain a CF custom tag. E.g.
<cfset a = '<model:sparkline id="1"/>'/>
And I'd like that to be evaluated into HTML and outputted. Not sure how/if I can do this.
Can you modify the custom tag? If so you can use the caller scope to set a variable in the calling page. So inside the custom tag you could do <cfset caller.a = "whatever" /> and that will set the value in the calling page's variables scope.
If you don't want to modify the custom tag, then you can use <cfsavecontent> to save the output to a variable. Example:
<cfsavecontent variable="a">
<model:sparkline id="1" />
</cfsavecontent>
Sean Coyne's answer is the correct one, provided the import is included within the same context as the cfsavecontent tag:
<cfimport taglib="./tags" prefix="model">
<cfsavecontent variable="a">
<model:sparkline id="1" />
</cfsavecontent>
<cfoutput>#a#</cfoutput>
Will result in the dynamically evaluated output of the sparkline customtag.
It's impossible to OUTPUT the code and have it execute. OUTPUT just means output. It doesn't mean "run".
The only way to get CF code to be executed by CF is to follow normal channels:
* request a template;
* include a template;
* call a template as a custom tag or CFMODULE;
* call a method in a CFC;
* any others? ANyway, you get the point.
So if you have code that you create dynamically and want to execute... you need to write it to a file and then call it via the most appropriate of those mechanisms. Be warned though: running dynamic code like this has a fair overhead, as the code needs to be compiled before it's run, and compilation is not the fastest process in the scheme of things. The "best" thing to do here is to try to write and compile the file before it's needed, and only re-write the file it it needs updatng. Don't re-do it every request. But, ideally, don't do this sort of thing at all. One can usually approach things a different way.
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:
"RE: <cfif myData.general.legalName NEQ """"> {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s) {{docketString}}"
When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.
<cfsavecontent variable="subject">
<cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>
I also tried
<cfsavecontent variable="subject">
<cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>
And then I replace all the {{ }} with the appropriate values.
However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.
Any ideas?
The only way to dynamically evaluate code that you are creating at runtime is via writing it out to a file, and then executing it.
The easiest way would be to write it a .cfm page in the Virtual File System (probably name the file after a UUID, so it's unique), and then it where you need to run the contents.
I wouldn't normally advocate generating code at runtime like this, but it can be the most elegant solution in some cases.
As an alternative, instead of storing the CFML code in the database, you have a set of CFML email template files that get stored in a directory on your server, and in your database you simply record which template needs to be included either via cfinclude or cfmodule.
You can't dynamically evaluate CFML stored in a database without first writing it to file and then using <cfinclude> to include it.
Further to Mark's answer here is some psuedo code:
<cfset fileName = createUUID() & ".cfm">
<cfset fileWrite( fileName, [CODE_FROM_DB]>
<cfinclude template="#fileName#">
<cfset fileDelete( fileName )>
I have used code like this before with no problems. Anything in the Virtual File System flies as it is all run in RAM. For best practice do remember to delete the files created ;)
If you absolutely have to do this, look at the evaluate() function. This, essentially, fires up a new CF thread, compiles the string passed to it, runs it, and returns the result.
If at all possible, I would try to find a way to move your logic to the actual file being run, not the string from the database. I assume you are pulling the data based on some string you've already built, so you might consider appending something to it, so you are looking up subjectDotLegal and subjectDocketLegal or something similar.
Remember, evaluate() is slow, ugly, and can be dangerous (it will run anything passed to it!). If there's a way around it, I suggest you use it.
why not just use something like mustache?
http://mustache.github.com/
https://github.com/pmcelhaney/Mustache.cfc
it has the ability to not only do some of the logic that you want in your script dynamically. i really would suggest you check out the project and maybe even improve and contribute on it.
OH and just for the chance to be on a soapbox: I've been emailing Adobe for years saying that we need the ability to dynamically parse and render CFML. Sadly my cries have only gotten ignored. maybe if more people complained that this feature needs to be added, it would get the attention it deserves.
To give an example: Assume code.txt is a text file that contains the following (just to facilitate simulating CFML stored in a db): <cfoutput>#now()#</cfoutput>
The following code would work:
<cfset q = queryNew("code") />
<cfset queryAddRow(q,1) />
<cfset querySetCell(q, "code", fileRead(expandPath('code.txt')), 1) />
<cfdump var="#q#">
<cfset newCodeFile = expandPath('dynamic.cfm') />
<cfset fileWrite(newCodeFile, q.code[1]) />
<cfinclude template="dynamic.cfm" />
In OpenBlueDragon there is the render function, which can do this.
You can mimic this function in Railo by creating a custom built-in function that saves the file into RAM then cfincludes it, using the following code:
<cffunction name="render" output="Yes" returntype="string"><!---
---><cfargument name="Code" required="Yes" type="string"><!---
---><cfset local.mapping = {'/render_ram_resource':'ram://'}><!---
---><cfapplication action="update" mappings="#local.mapping#"><!---
---><cfset local.fileName = "/render_ram_resource/_render_" &
createUUID() & ".cfm"><!---
---><cffile action="WRITE" file="#fileName#"
output="#arguments.Code#"><!---
---><cfinclude template="#fileName#"><!---
---><cffile action="DELETE" file="#fileName#"><!---
---></cffunction>
(This looks unusual because it needs to allow output, but prevent extra whitespace, hence why all the comments. Unfortunately SO's syntax highlighting seems to be confused by them.)
If you need an ACF-compatible solution, you'll need to use the regular filesystem and a pre-created mapping. (Well, in ACF9 and above you can use the RAM virtual filesystem, but afaik you can't create mappings on the fly like this.)
There's a better way, namely using in memory files. This way you don't have any I/O on the disk and therefore much faster:
For tags that take logical path, define mapping in Administrator. Execute in-memory CFM pages using the cfinclude tag:
Create a mapping for ram:/// so that it can be used in the tags. In this example, /inmemory is the mapping that points to ram:///.
For tags that take absolute path, specify the syntax as provided in the following example:
You can also delete the file from the ram usinf cffile and action delete.
Here's how I stored my header and footers for all pages in a record. This code can go at the top of each page. But I have it in the APPLICATION.cfm and it seems to be working great.
The key here is not use #pound# signs on your expressions. User [square braces]. The code will pick them and evaluate them and return the result back to the template.
It will substitute the number 0 if it can not evaluate an expression as a means of error handling.
<CFSET FooterID=1234> <!-- ID of the record you want to use -->
<CFQUERY NAME="StoredHeader" Datasource="DS1">
Select Body from templates where id=#FooterID#
</CFQUERY>
<CFSET Parse=StoredHeader.Body>
<CFLOOP CONDITION="FindNoCase('[',Parse,1) GT 0">
<CFSET STB=FindNoCase('[',Parse,1)>
<CFSET ENB=FindNoCase(']',Parse,1)>
<CFIF ENB-STB GT 0>
<CFSET BracketExp=Mid(Parse,STB+1,ENB-1-STB)>
<CFTRY>
<CFSET BracketValue=Evaluate(BracketExp)>
<CFSET Parse=ReplaceNoCase(Parse,'['&BracketExp&']',Evaluate(#BracketExp#))>
<cfcatch type="any">
<div>'Using ZERO 0 for missing <cfoutput>#BracketExp#' </cfoutput> </div>
<CFSET Parse=ReplaceNoCase(Parse,'['&BracketExp&']','0')>
</cfcatch>
</CFTRY>
</CFIF>
</CFLOOP>
<CFSET Footer=Parse>
<cfoutput>FOOTER</cfoutput>
I would try the built-in QuoteName function.