Matthew Weier O'Phinney wrote:
-- Ralf Eggert<[EMAIL PROTECTED]> wrote
(on Friday, 28 November 2008, 06:23 PM +0100):
What I've started doing and recommending is to attach forms to your
model, and to use forms for model validation.
Thanks for your reply. Your approach sounds very sensible to me. But I
am not sure how you handle different forms for the same model. In my
example I have different forms which use the same validator and filter
definitions for the same fields.
Would you define the validators and filters for the username field in
all three forms? If you want to change these rules for the username
field you need to change these definitions in each form, don't you?
I typically define forms explicitly as discrete classes -- and the same
for elements. What I would suggest is that if there are common elements
you use across multiple forms that will be using the same
validators/filters/decorators/etc... then create a custom element:
class My_Form_Element_Username
{
public function init()
{
$this->addValidators(array(
'Alnum',
array('StringLength', false, array(6, 20)),
));
$this->setRequired(true);
}
}
In your form classes, use these custom elements. That way, if you change
the rules for a single element type, it will propogate to all forms that
use it.
And how do you handle different forms for the same model, say the create
form is different than the update form?
A single model can certainly have multiple forms -- the example I
displayed was just a simple one.
Have a getter for each form, or have getForm() accept an argument
indicating the form to retrieve.
Wouldn't be better a reversed relationship, i.e. a series of forms have
a setter setModel() and the whole validation
logic is inside the model (the place that I think is the most appropriate) ?
Ralf said "And how do you handle different forms for the same model, say
the create
form is different than the update form?"
IMHO this is a case where validation should stay in the model and the
form would have access to the validators
in the model. Also, there is no need to duplicate a setForm() method or
add parameters to it.
I came to this conclusion after I realized that Zend_Form is just a very
specialized controller + view. The only thing
missing is the model.