Bind model to the Zend_Form…

In my pre­vi­ous post I have described how to fill model with val­ues from the Zend_Form. But reverse pro­cess is also very import­ant. If you are using Zend_Db_Table you prob­ably will not need any spe­cial meth­ods as you can use Zend_Form::setDefault($array) built-in method. But if you are work­ing with Doc­trine ORM or some­thing sim­ilar you’ll need to use your own method to read model’s data and put it into the form. So today I’m going to show how to pop­u­late field val­ues of Zend_Form from model. With tra­di­tional example applic­a­tion :))

I will use the same ele­ment bind­ings as in pre­vi­ous post about bind­ing Zend_Form to the model. So if you didn’t read pre­vi­ous post, please read it first just to under­stand where bind­ings are got from. For those of you who read it before I will remind it a little. We defined a pro­tec­ted prop­erty $_binding for our My_Form class which stores a hash of 'element_name' => array('model_property_name', 'callback'). So we’ll base on top of code from pre­vi­ous post.

OK. This post will be much shorter than pre­vi­ous one :)) First of all I have defined a helper method to pre­pare a value by it’s path:

class My_Form
{
    // ...

    /**
     * Gets value of node specified by path
     *
     * @param  array $array
     * @param  mixed $path
     * @return mixed
     */
    protected function _getValueByPath($array, $path)
    {
        list($curr, $path) = (array) $path;
        return (null !== $path)
            ? $this->_getValueByPath($array[$curr], $path)
            : $array[$curr];
    }

    // ...
}

This method is a com­pli­ment­ary for the _setValueByPath() from pre­vi­ous post, so you can look it’s dis­cus­sion to under­stand why this method was needed. Now, the main part of this post — the reader method:

class My_Form
{
    // ...

    /**
     * Set values of form elements with corresponding model properies.
     *
     * @param  Doctrine_Record $model
     * @return My_Form self-reference
     */
    public function read(Doctrine_Record $model)
    {
        foreach ($this->getElements() as $name => $element) {
            if ( ! array_key_exists($name, $this->_bindings)) {
                continue;
            }

            list($prop, $path) = (array) $this->_bindings[$name];

            $value = (null !== $path)
                   ? $this->_getValueByPath($model->$prop, $path)
                   : $model->$prop;

            $element->setValue($value);
        }

        return $this;
    }

    // ...
}

For those of you who use Zend_Db_Table and by some reason can’t use built-in Zend_Form::setDefaults() I have pre­pared sim­ilar method for using with arrays:

class My_Form
{
    // ...

    /**
     * Reads array of $data setting corresponding element's values
     *
     * Same as {@link My_Form::read()} but reads an array of data.
     *
     * @param  array $data
     * @return My_Form self-reference
     */
    public function setModelData($data)
    {
        foreach ($this->getElements() as $name => $element) {
            if ( ! array_key_exists($name, $this->_bindings)) {
                continue;
            }

            list($prop, $path) = (array) $this->_bindings[$name];

            if ( ! array_key_exists($prop, $data)) {
                continue;
            }

            $value = (null !== $path)
                   ? $this->_getValueByPath($data[$prop], $path)
                   : $data[$prop];

            $element->setValue($value);
        }

        return $this;
    }

    // ...
}

That’s all. I guess there’s no need to describe every single char as I think everything is clear more then enough. Any­way if you have any ques­tions — fell free to ask.

UPD [2010/03/08] Fixed small typo.

  • del.icio.us
  • Google Bookmarks
  • Identi.ca
  • Twitter
  • Technorati
  • Digg
  • Slashdot
  • Facebook
  • MisterWong
  • Reddit
  • StumbleUpon
  • Mixx
  • HelloTxt
  • LinkedIn
  • PDF
  • email
  • Print
This entry was posted in Zend Framework and tagged , , , . Bookmark the permalink.

One Response to Bind model to the Zend_Form…

  1. Pingback: binding method

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>