jkulak
jkulak

Reputation: 908

Create form for several actions in Zend Framework

I have an upload form, which is displayed on overlay/lightbox/toplayer. It's available only for several actions in several controllers.

Creating this form needs ~6 lines of code and needs access to REQUEST object to grab params from it.

Where should I put this code, so I could easily create my form in actions I need.

Upvotes: 1

Views: 107

Answers (1)

drew010
drew010

Reputation: 69957

I'd put this functionality in an Action Helper. An action helper can be called directly from any controller action (and is lazy loaded) and action helpers have access to everything the controller action does including the request object and view.

Example:

<?php

class My_Action_Helper_FormCreator extends Zend_Controller_Action_Helper_Abstract {
    public function direct($options = null)
    {
        $request  = $this->getRequest();
        $view     = $this->getActionController()->view;
        $form     = new Application_Form_SomeForm();

        // set form options here...

        $view->form = $form; // optional - assign form directly to the view

        return $form;
    }
}

Place that code in library/My/Action/Helper/FormCreator.php (or where desired and change the class name).

Then, in your actions, call it like this:

$form = $this->_helper->FormCreator();

Lastly, we need to tell the helper broker where to find this action helper. To do so, add this to your bootstrap:

protected function _initActionHelpers() {
    Zend_Controller_Action_HelperBroker::addPrefix('My_Action_Helper');
}

Hope that helps.

Upvotes: 2

Related Questions