Using Zend_Form in Magento

As we all know, Magento is built using some of the Zend Framework library. However, that doesn’t mean you can go straight into a controller and start programming like you would ZF. However, preparing your Zend_Form in order to work in Magento is pretty straigtforward.

Magento’s controllers do not have a view! So your form will fail to render! To fix this, we override the __toString() method:

 *  Overridden because Magento doesnt have the zend view
public function __toString()
    return  $this->render(new Zend_View());

Now your form will work in your magento controller.  If you are new to Magento like I am, you’ll also need to know how to instantiate the form, send the form to the view, and how to display it once we are in the view! In the controller:

public function indexAction()
 // new My_Form_Class(); also works here, but this is how Magento does it, from the xml config.
 $this->form = Mage::getModel('madskull_feedback/form'); 

   $data = $this->getRequest()->getPost();
     // get sanitised data
     $data = $this->form->getValues();

  $this->getLayout()->getBlock('madskull_feedback.form')->setData('form', $this->form);

On the .phtml file, it’s a piece of cake:

echo  $this->getData('form');

There you go! Full Zend_Form goodness! Have fun!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s