MVC Form Layer

Forms are a tricky part of any Model-View-Controller (MVC) application. They incorporate validation, presentation, and security logic that spans all tiers of the application. Separating these concerns is difficult but important. I’ll walk through how I use Zend_Form in Zend Framework 1, but the same principles should apply to any MVC application.

A User account form

For this article, imagine a basic form for users to create or update their account. To keep things simple, I’ve replaced some of the logic with // TODO: comments. Let’s start with the form itself.

Because the form field names are referenced outside of this class, I assign them to class constants. The populateFromUser() function will receive a User object and copy its attributes to the appropriate form fields. Other populateFrom*() functions could be added to accommodate other objects.

The User model

Next we look at the User model. As a foundation I used the approach suggested by Matthew Weier O’Phinney, Zend Framework Project Lead, in “Using Zend_Form in Your Models”. Here’s the User model and its base class.

Compared to Matthew’s example, I removed the $_forms property and added support for form options and multiple form bases.

The controller

Finally, we’ll tie everything together in the controller.

The controller retrieves an instance of Application_Model_User and gets an Application_Form_Account from it. If loading the form for the first time, it is populated with the user’s attributes. If the user submits the form, the form and its contents are passed to the User model to validate and save.

Displaying the form

To cap off this example, let’s see the view that renders this action.

Presentation concerns like the submit button and form decorators are handled here because they aren’t pertinent to the form-model interaction.

Conclusion

With this approach, all form operations are done in the appropriate tier. The form populates itself from models, the model digests all of the form data, and the view handles all of the rendering. This keeps the form flexible and reusable.

Leave a Reply

Your email address will not be published.