CFScript Snippets

useful CFScript blocks that I use quite a lot

MySQL Query

view plain print about
1<cfscript>
2// create query string
3
strSelectRows = 'SELECT col1, col2, col3 FROM table WHERE';
4
5// create query, assign datasource, assign query string, execute and capture returned result
6
qrySelectRows= new Query();
7qrySelectRows.setDataSource(APPLICATION.dsn);
8qrySelectRows.setSQL(strSelectRows);
9qrySelectRows= qrySelectRows.Execute().getResult();
10
11// dump results out
12
writeDump(qrySelectRows);
13
</cfscript>

Query of queries

view plain print about
1<cfscript>
2// query of queries
3
stuffQuery = new Query();
4stuffQuery.setDbtype('query');
5stuffQuery.setAttributes(stuff = tableName);
6stuffQuery.setSQL("SELECT DISTINCT thing FROM stuff");
7stuffQuery= stuffQuery.Execute().getResult();
8
</cfscript>

HTTP POST Request

view plain print about
1<cfscript>
2
3strURL = 'https://www.google.com/accounts/ClientLogin';
4

5// create service and set attirbutes, such as method and url
6
httpRequest= new http();
7httpRequest.setMethod('
POST');
8httpRequest.setCharset('
utf-8');
9httpRequest.setUrl(strURL);
10
11// add form fields httpRequest.addParam(type="formfield",name="username",value="#strUsername#");
12
httpService.addParam(type="
formfield",name="password",value="#strPassword#");
13// make the request and dump out the response
14
httpResponse= httpRequest.send().getPrefix();
15writeDump(httpResponse.fileContent);
16</cfscript>

Component outline

There's a million different ways of doing this. Most of the time you can use a mix of comments to make definitions and quoted attributes in the function name. I don't know if you can define the arguments with comments, buy you can definately move return type, access type, hint between the inline quoted definition and the comments before the function. But this is my favourite way of doing it, hints in the comments, everything else on the function name line

view plain print about
1/**
2*@accessors true
3*/

4component {
5
6    property type="string" name="username" default="";
7    property type="string" name="password" default="";
8
9    /**
10    *@hint Initializes component.
11    */

12    public function init(
13        required string username="",
14        required string password="") {
15
16        setUsername(ARGUMENTS.username);
17        setPassword(ARGUMENTS.password);
18
19        return this;
20    }
21}

Some mroe blog posts on CFScript components: