This was a simple request, but I thought I'd share the code in case any other beginners would find it interesting. Joe asks:
So as Joe pointed out, it's rather simple to use cfdirectory to create a list of files. Joe mentioned checkboxes and a simple form, so let's look at that part of the script first:I was after a method of being able to select results from a cfdirectory query using a form check box, then once a "delete selected" button is pressed it will then go on to delete them from the directory.
I currently have a page displaying all the files and folders now I just need a way so delete the selected records could you please help?
<cfset directory="#expandPath('.')#">
<cfdirectory action="list" directory="#directory#" name="entries" type="file">
<cfoutput><form action="#cgi.script_name#" method="post"></cfoutput>
<table>
<cfoutput query="entries">
<tr>
<td><input type="checkbox" name="files" value="#name#" /></td>
<td>#name#</td>
</tr>
</cfoutput>
</table>
<input type="submit" value="DELETE" />
</form>
Normally the directory variable would point to some other folder instead of the current folder. This script would actually let you delete the script itself, which is probably not a good idea. Notice that I filtered by files. You can actually perform a recursive delete on a directory, but since Joe mentioned files I figured I'd keep it at that.
Notice next to each file we use a checkbox with the name files. When the form is submitted, each and every file will exist in the form value, files. If the user selects multiple files, then the values will be a list. Here is how I processed the form submission:
<cfif structKeyExists(form, "files") and len(form.files)>
<cfloop index="f" list="#form.files#">
<cfif fileExists(directory & "/" & getFileFromPath(f))>
<cffile action="delete" file="#directory#/#getFileFromPath(f)#">
</cfif>
</cfloop>
</cfif>
Nothing crazy here. Note though that I go the extra step to ensure the file exists before I delete it. In theory it is possible someone else could have deleted the file. (And to be real anal, I should use a cflock as well.)
As I said - easy stuff, but hopefully this example will help Joe. I'll print the entire sample below. Before doing so, don't forget that any web based application that lets you delete files is a risky. Please be sure you know what your doing before deploy code like this.
<cfset directory="#expandPath('.')#">
<cfif structKeyExists(form, "files") and len(form.files)>
<cfloop index="f" list="#form.files#">
<cfif fileExists(directory & "/" & getFileFromPath(f))>
<cffile action="delete" file="#directory#/#getFileFromPath(f)#">
</cfif>
</cfloop>
</cfif>
<cfdirectory action="list" directory="#directory#" name="entries" type="file">
<cfoutput><form action="#cgi.script_name#" method="post"></cfoutput>
<table>
<cfoutput query="entries">
<tr>
<td><input type="checkbox" name="files" value="#name#" /></td>
<td>#name#</td>
</tr>
</cfoutput>
</table>
<input type="submit" value="DELETE" />
</form>