On Thu, Dec 4, 2008 at 21:07, Mary Nicole Hicks <
[EMAIL PROTECTED]> wrote:

>
> I currently have a form with validation, and no validation on the object I
> am
> saving. The problem I have is that I am looking at having many more forms.
> It would make more sense to me if this validation is done when the object
> is
> saved rather than on the forms.
>
> Can anyone give an example on how I can have the validation happen when I
> save the object, but display failed validations as the form does (Per form
> element)?



In my application I have action helper getForm($name). This heleper store
forms in private field $_forms = array();
For now I  use it in model as static helper, but I think about refactor it.

In controller (edit action):

$model = $this->_helper->getModel('artist');
$form = $model->getForm('artist');

if ($this->_request->isPost()) {
    if (true === $model->add($this->_request->getPost())) {
        //do something
    }
} else {
    $artist = $model->getTable('artist')->find($artistId)->getRow(0);
    if (null !== $artist) {
        $form->populate($artist->toArray());
    } else {
        //do something, row with $artistid not found;
    }
}

$this->view->form = $form;

------
in model:
public function add(array $data)
{
    $form = $this->getForm('artist');
    if (!$form->isValid($data)) {
        return false;
    }

    $values = $form->getValues();

    //check if this is new row, or edit,
    // do something you need with values,
    // store values where you want

    return true;
}
-----
in view just simply:

<?= $this->form ?>


if $form in controller and $form in model is the same instance of form and
you validate form in model,
in view will be properly render.

This works for me.

It's based on discussion form lists, pastebin, and bugapp. ;-)

Approach from Matthew's pastebin don't look good for me. Too many logic in
view. Can't use it when my views are xsl files.

kind regards,

-- 
Paweł Chuchmała
pawel.chuchmala at gmail dot com

Reply via email to