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.
Almost three years since you posted this...but this really helped me today :) Thanks!!!
ReplyDeleteinteresting blog. It would be great if you can provide more details about it. Thanks you
ReplyDeleteiMarque - Form Processing
Thanks
ReplyDelete