Improving the Tutorial: Using the Same View for Multiple Actions in CFWheels
This time, I'll talk about how we could factor out view logic so that the profile form can be used for both the
edit actions. With all of this MVC goodness, we should be able to do some refactoring easily, shouldn't we?
Using the same view for
First, here’s the view at views/users/new.cfm:
And here’s the view at views/users/edit.cfm:
The first difference that we can notice is the title contained in the
<h1> tags at the top of each file. Assuming that we don’t factor them out into a layout (which may be the best idea), we can set that as a variable in the controller and let it decide what to show in each case. Either way, the value would need to be set in the controller at that point.
The same may go for the success message. That may go in a layout file as well. But as it turns out, we could just have it available in both scenarios. It won’t show unless that value is set in the Flash anyway.
Lastly, it doesn’t matter if the
id value is included as blank in the
add action, so we can just include it in both scenarios as well.
Those changes said, we can write a single view file. Let’s call it views/users/form.cfm.
Notice that I also use
<cfparam> tags at the top of the view file to check for values that are expected from the controller. It’s a preference of mine to do this because it just makes everything more self-documenting.
This view file also requires a
submitLabel value to be used in the
submitTag() form helper and a
formAction value to be used to define which action to call.
So here’s what the
edit() methods in the controller at controllers/Users.cfc would look like to accommodate the view changes:
Look, the repetition is gone, and now we have one less view file! We just set the values needed by each action and call
renderPage() with the name of the view file to run,
There are ways to create partials and helpers to factor some of this out application-wide. But I wanted for you to see the process of factoring code up one level. Perhaps we shall explore in a future post.