Reputation: 4118
In Zend Frameworks tutorials, I can see form processing code like
if ($request->isPost()) {
$formData = $request->getPost();
$code = $request->getParam("code");
$url = $request->getParam("url");
if ($form->isValid($formData)) {
// here goes code to determine insert/update action,
//retrive record data
//and perform relative database operation
This code repeats for many forms. I am trying to make form handling better, yet not to over-engineer it. So far I have moved this code from Controllers into Form object. But the code still diplicates for different form types.
My question is this - Should I prefer to keep form handling code duplicate or write some ProcessSubmit() Zend_Form method that will be used by all subclasses? I had experience that abstraction is not always good and sometimes you end up synching two classes that shoul've been different from beginning.
ZF examples demonstrate duplicate code, so I wonder if this duplicity is justifed (at least for small 3-4 form sites) or needs to be avoided by all means.
P.S. This task seems to be pretty common, I wonder if I do double work and there is already a ZF class for CRUD specific form handling.
Upvotes: 4
Views: 185
Reputation: 1839
If you want to use "thin controllers/fat models" after validating the form just pass the whole form or form values to your model.
As for control structures in your controller they are "normal".
Upvotes: 0
Reputation: 25263
What I have actually done was to move validation into the domain objects (or model layer), and then my domain layer implements a save() method.
While I don't use Zend_Form in my domain layer, I have noticed that others will implement a Zend_Form instance in their domain models so that they can present a consistent form everywhere for each domain model. Personally, I feel that this couples domain objects to the presentation layer too much.
Instead, I do use Zend_Filter_Input as the backbone for validation in my domain objects.
Upvotes: 1
Reputation: 83642
Perhaps an action helper could, well, help you out here:
class App_Controller_Action_Helper_ProcessFormSubmit extends Zend_Controller_Action_Helper_Abstract
{
public function isValid(Zend_Form $form)
{
if ($this->getRequest()->isPost()) {
return $form->isValid($this->getRequest()->getPost());
} else {
return false;
}
}
public function direct(Zend_Form $form)
{
return $this->isValid($form);
}
}
This allows you to handle form submission processing like this:
// or: if ($this->_helper->processFormSubmit->isValid($form)) {
if ($this->_helper->processFormSubmit($form)) {
// here goes code to determine insert/update action,
//retrive record data
//and perform relative database operation
}
This can be extended to your needs, e.g. automatic error handling and so on...
Upvotes: 2