Archive

Archive for August, 2009

CFWheels — Fixing the Controller and View

August 30th, 2009

Last time, we setup our route, and now if you go to: http://localhost/index.cfm/ads/3, you won’t get an error. But, just like on Page 63 of Head First Rails, the ads are blank and the page is kind of boring — There’s no data.

First, we need to fix our controller at /controllers/Ads.cfc. Make sure your show function looks like:

[cf]
<cffunction name="show">
<!— Find the record —>
<cfset ad = model("Ad").findByKey(params.key)>
</cffunction>
[/cf]

When Wheels created the model, it automatically adds the findByKey method. All we have to do is tell it which key we want, and params.key has the key value!

We still need to fix /views/ads/show.cfm to display the data. Change this file to:

[cf]
<cfoutput>
<p><b>Name:</b>#ad.name#</p>
<p><b>Description:</b>#ad.description#</p>
<p><b>Price:</b>#ad.price#</p>
<p><b>Seller Id:</b>#ad.seller_id#</p>
<p><b>Email:</b>#ad.email#</p>
<p><img src="#ad.img_url#"/></p>
</cfoutput>
[/cf]

Pretty neat. Just put the values in the view and wrap it up in a <cfoutput> tag! Wheels handles the hard part of getting the data from the database into the model.

Go back to: http://localhost/index.cfm/ads/3, and you’ll see that the data is now being correctly displayed.

Clarke Bishop CFWheels, ColdFusion

CFWheels — How to Setup and Use Routes

August 30th, 2009

Routes offer a way to map web URLs to specific controllers in your application. It’s one place where you might use configuration in CFWheels.

There’s a good section in the CFWheels docs on Using Routes.  But, I’m going to continue following along with the examples in Head First Rails, starting on page 56.

If you try a URL like this: http://localhost/index.cfm/ads/3, Wheels will give you an error: Could not find the view page for the ‘3′ action in the ‘ads’ controller. That’s because, Wheels is looking for the Ads controller with the “3″ action. Rails would complain that there is no action (Method in the Ads controller) called ‘3′. But, Wheels is smarter and just goes straight to the view. We don’t have a ‘3′ method in Ads.cfc, but Wheels still tries to load a view from /views/ads/3.cfm. The file isn’t there, so it throws an error.

Setting up a Route will let us fix this! Open up /config/routes.cfm. It defaults to something like:

[cf]
<cfset addRoute(name="home", pattern="", controller="wheels", action="congratulations")>
[/cf]

Did you ever wonder how you got to that nice congratulations page when you just go to: http://localhost/? What happens is that our route, the “home” route, says, that if the URL pattern is “” (Blank String), Wheels should go the the wheels controller, and run the action congratulations.

Take a peek at /controllers/Wheels.cfc. Sure enough, there is a congratulations method that loads up info on the current version of Wheels. And, then of course, it looks for the view in /views/wheels/congratulations.cfm. The file is already there as part of the default Wheels installation. If you open it up, you can see the HTML code including the place where it inserts the version information Wheels got from the controller.

The default routes.cfm file is nice, but lets make some changes!

[cf]
<cfset addRoute(name="ads", pattern="/ads/[key]", controller="ads", action="show")>
<cfset addRoute(name="catchall", pattern="[path]", controller="redirect", action="index")>
<cfset addRoute(name="home", pattern="", controller="redirect", action="index")>
[/cf]

It’s important to understand that Wheels goes through the routes in order from top to bottom. As soon as it finds a match, it goes to the appropriate controller. Here’s how you interpret this route.cfm:

  • Ads. If the URL pattern looks like: http//localhost/index.cfm/ads/3, go to the show action in the ads controller. Did you notice the pattern includes [key]? This tells Wheels to set the key parameter to whatever is in the URL — 3 in this case.
  • Catchall. If the URL doesn’t match the Ads pattern, Wheels will try the next pattern. This pattern matches [path]. In other words, it matches anything, and puts the value in the path parameter. Actually, it doesn’t put everything in the path paramter — Just the part before the next slash, “/”. http//localhost/index.cfm/xxx/yyy/zzz/3 will only have “xxx” in the path parameter. A route like this is a good one to add to catch any unknown URLs a user might enter — Sort of like a 404 Error page.
  • Home. If the URL pattern  is blank, we’ve got one more route to cover that case. Remember, the pattern is just the stuff that comes after http//localhost/index.cfm/.

Ultimately Routes just offer a convenient way to map a URL to a controller. They are useful for having prettier URLs that make more sense to the users.  You can always use query params in your URL and completely bypass routes. This URL, http://localhost/index.cfm?controller=ads&action=show&key=3 directly specifies the controller and action, so there’s no need for Wheels to check the route!

Clarke Bishop CFWheels, ColdFusion

CFWheels — Creating a Custom Controller and View

August 27th, 2009

We’re on Page 52 of Head First Rails, and we need to create a custom Controller and View.

I’m going to keep following the book, but there is a great tutorial that covers the same ideas over on the CFWheels website.

Convention Rules!  CFWheels has conventions for almost everything. As long as you follow the conventions, things just work naturally.

For example, look at a URL like this http://localhost/ads/show/5. CFWheels will automatically interpret this to run the show function in the ads controller. The number 5 is passed as a “key”.

Before I keep going, I have to touch on URL rewriting. The URL I just used as an example will only work if your server supports full URL rewriting. I’m using the ColdFusion development server, and it only offers “partial” URL rewriting. So, I have to use a URL like this: http://localhost/index.cfm/ads/show/5. Notice that index.cfm has to be inserted in the URL!

You can also specify the Controller and Action like this: http://localhost/index.cfm?controller=ads&action=show&key=5. Doing it this way will always work. It bypasses routes and any server URL rewriting problems. You might want to just use this form of URL while you are learning or if you are debugging a problem.

In any case, the idea is to run the show function in the ads controller. CFWheels will look for Ads.cfc in the controller folder, and will look for the show function inside Ads.cfc.

Then, it will run the show function and load the view. It will expect there to be a view file in /views/ads named show.cfm to match the function you called.

But, guess what? If you don’t create the Ads.cfc controller, CFWheels, will still try to run the view. Normally, you’ll want the controller to get some data for you, but if not, you could skip the controller altogether.

Here’s my controller code for /controllers/Ads.cfc:

[cf]
<cfcomponent extends="Controller">

<cffunction name="index">

</cffunction>

<cffunction name="show">

</cffunction>

</cfcomponent>
[/cf]

Later, we’ll add some functionality to the controller, but I’m following the book. And, for now, the only two actions we need are index and show.

At this point, you could try to go to http://localhost/index.cfm?controller=ads&action=show&key=5. But, you’d get a Wheels error because there is no view file.

Here’s my view code for /views/ads/show.cfm:

[cf]
<p><b>Name:</b></p>
<p><b>Description:</b></p>
<p><b>Price:</b></p>
<p><b>Seller Id:</b></p>
<p><b>Email:</b></p>
<p><img src=""/></p>
[/cf]

I know, this doesn’t do much either, but we’ll add on. Be Patient!

Now, if you go to http://localhost/index.cfm?controller=ads&action=show&key=5, you’ll see the lovely static view file you just created.

Next time, we’ll look at routes some more, and eventually, we’ll actually make this app work.

Clarke Bishop CFWheels, ColdFusion

CFWheels — Creating a Custom Model

August 25th, 2009

Continuing the series on using Head First Rails to learn CFWheels, lets move on to Chapter 2 — Beyond Scaffolding. We are going to create the MeBay application!

Starting on Page 45 in Head First Rails …

Whether we use scaffolding or not, we still have to create the database. In Rails, you do this with the script/generate model command and then running rake. But, in CFWheels, it’s easiest to just use SQL and create the database directly. Here is some mySQL code to create the needed ads table.

[sql]

CREATE TABLE `ads` (
`id` INTEGER PRIMARY KEY NOT NULL auto_increment,
`name` varchar(255),
`description` text,
`price` decimal,
`seller_id` integer,
`email` varchar(255),
`img_url` varchar(255),
`created_at` datetime,
`updated_at` datetime
);
[/sql]

Later on, we’ll want to populate the table with some sample data, so let me go ahead and show the full SQL that creates the table and adds the test data:

[sql]
DROP TABLE IF EXISTS `ads` ;
CREATE TABLE `ads` (
`id` INTEGER PRIMARY KEY NOT NULL auto_increment,
`name` varchar(255),
`description` text,
`price` decimal,
`seller_id` integer,
`email` varchar(255),
`img_url` varchar(255),
`created_at` datetime,
`updated_at` datetime
);
INSERT INTO `ads` VALUES(1,’Typewriter’,'Old manual typewriter. Many years useful service. Works best with a bottle next to it.’,71.95,54,’dhammett@email.com’,'http://homepage.mac.com/david_griffiths/typewriter.png’,”,”);
INSERT INTO `ads` VALUES(2,’Football’,'Some strings frayed.’,74.02,45,’marty@googlemail.com’,'http://www.freefever.com/freeclipart/clipart/football2.gif’,”,”);
INSERT INTO `ads` VALUES(3,’Moosehead’,'Slightly moth-eaten. One of the antlers is broken and there’’s a strange buzzing sound behind the eyes…’,2978.25,56,’kathy@hotmail.com’,'http://saloon.javaranch.com/ubb/moosefly.gif’,”,”);
INSERT INTO `ads` VALUES(4,’Desk’,'Milk desk - go…’,4800,123,’andy@allmail….’,'http://picasaweb.goog…’,”,”);
INSERT INTO `ads` VALUES(5,’Door curtain’,'Beaded door cu…’,11,773,’dawn@hotmail….’,'http://www.freewebsit…’,”,”);
INSERT INTO `ads` VALUES(6,’Apple Newton’,'Still works! M…’,25,2,’ahertz@differ…’,'http://www.differnet….’,”,”);
INSERT INTO `ads` VALUES(7,’Sinclair C5′,’Battery flat t…’,372.06,346,’clive@sinclai…’,'http://www.ebay.com/w…’,”,”);
INSERT INTO `ads` VALUES(8,’Edsel’,'Never used aut…’,355,755,’bing@badabing…’,'http://pages.google.c…’,”,”);
INSERT INTO `ads` VALUES(37,’Diamond’,'203.4 carats, grade D pear cut diamond. Low price for quick sale. Owner leaving the country.’,1000000,5234,’pink@panther.com’,'http://’,”,”);
[/sql]

It’s easy enough to manually create the Model, but for convenience, let’s use the scaffolding plugin anyway.

Click the Scaffold link at the bottom of any CFWHeels page –  In the debug section, next to Plugins. Then, on the scaffold page, enter ad as the Object name, select Model from the Type drop down, and click Generate. Remember, the table is named ads (plural with an “s”), but the the model is named ad (singular).

Now, open /models/Ad.cfc. You’ll see something that looks like:

[cf]
<cfcomponent extends="Model">

<!— All initialization related tasks are done in the "init" function which is run the first time the model is requested. —>
<cffunction name="init">
</cffunction>

</cfcomponent>
[/cf]

That’s all it takes to create a model! Your model must extend Model.cfc — That’s where all the CFWheels goodness happens. Other than that, all you need is an init function. Later on, you can use the init function to add extra capabilities, but for now, all that’s needed is a blank init function!

Clarke Bishop CFWheels, ColdFusion