Home > CFWheels, ColdFusion > CFWheels — Adding a Custom Index Page

CFWheels — Adding a Custom Index Page

September 6th, 2009

Starting on Page 73 of Head First Rails, we need to add an index page so that people can find the pages they want!

First, let’s add a new route so that http://localhost/index.cfm/ads/ goes to the new index action we’ll add in a minute.

Open up /config/routes.cfm, and change it to:

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

Notice the new route on line 2: <cfset addRoute(name=”adsNoKey”, pattern=”/ads/”, controller=”ads”, action=”index”)>. CFWheels checks the routes in order. So, if the URL pattern matches /ads/[key], it will go to the show action. But, if the key isn’t there, it matches the /ads/ pattern and goes to the new index action.

Now, we need to add an index action to the controller and then an index.cfm view. Open up /controllers/Ads.cfc and add the new index function. Leave the show function alone.

[cf]
<!— ads/index —>
<cffunction name="index">
<cfset ads = model("Ad").findAll()>
<cfdump var="#ads#"><cfabort>
</cffunction>
[/cf]

Notice the that we set ads = model(”Ad”).findAll().  This tells Wheels, to go get the Ad model, and findAll the data — Pretty Powerful! The data comes back as a ColdFusion query object.

For testing, put the <cfdump>line  in your controller, and send your browser to:  http://localhost/index.cfm/ads/. You’ll see the query dumped out in all its glory! This is a pretty good debugging trick. Add a <cfdump> to your controller to see what variables and data the controller is passing to the view. Remove the <cfdump> line, and let’s go create the view.

Go create /views/ads/index.cfm:

[cf]
<h1>All Ads</h1>
<ul>
<cfoutput query="ads">
<li>#linkTo(text="#ads.name#", route="ads", key="#ads.id#")#</li>
</cfoutput>
</ul>
[/cf]

Pretty simple! Specifying the query attribute in <cfoutput> makes this just like a <cfloop>. You end up with a bunch of List Items (<li>) — One for each record in the query we got from the controller.

linkTo() is another cool Wheels helper function. You could just use an <a> tag. However, using the linkTo() function is a best practice because it makes your application more portable. We specified the “ads” route in the function. If, later on, we changed our subfolders or URL rewriting, everything would still work.

That’s it. Send your browser to: http://localhost/index.cfm/ads/ and you should see a list of ads. Each ad will have a link that takes you to the show action and displays the ad.

Clarke Bishop CFWheels, ColdFusion

  1. No comments yet.
  1. No trackbacks yet.