Thursday, August 12, 2010

Populate Zend Form with Doctrine Entity

One basic task with Doctrine and Zend_Form is the ability to populate zend form with doctrine entity on the fly. For example, in a blog application, basically you will have an edit page to edit your blog and that particular blog in DDD scenario will be an entity let's say Project_Entities_Blog. Now that blog entity contains all the information (fields) that we need to pre-populate the fields in our zend form.

Manually set the form data

// Get the blog entity from entity manager. 
$blog = $this->_em->find('Project_Entities_Blog', 1);

// Create an array of blog information.
$formData = array(
   'title'        => $blog->getTitle(),
   'content'  => $blog->getContent(),
   'date'      => $blog->getDate()
);

// Populate zend form. 
$form->populate($formData);
$this->view->form = $form;

This method is fine for a basic small form but it'll become tedious if we have a large form with so many fields hence for the second method.

Get an array of properties

First, we create additional method to our entity called toArray().

/**
 * @Entity
 * @Table(name="blog")
 */
class Project_Entities_Blog
{
    public function toArray()
    {
        return get_object_vars($this);
    }
}

This method makes use of php's get_object_vars() which actually return an associative array of the current object's properties.

Now in the controller,

class BlogController extends Zend_Controller_Action
{
    public function editAction()
   {
        $request = $this->getRequest();
        $form = new Project_Form_Blog();
      
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($request->getPost())) {
                // form processing. 
            }
        } else {
            // Get the blog entity from entity manager. 
            $blog = $this->_em->find('Project_Entities_Blog', 1);

           
            // Populate zend form with blog's array of properties.
            $form->populate($blog->toArray());
        }
        
        $this->view->form = $form;
    }
}

Now that's much better, we populate zend form directly from our entity.

3 comments:

  1. Almost three years since you posted this...but this really helped me today :) Thanks!!!

    ReplyDelete
  2. interesting blog. It would be great if you can provide more details about it. Thanks you








    iMarque - Form Processing

    ReplyDelete