Search code examples
zend-frameworkzend-formzend-view

Access views url function in Zend_Form


I have some Forms that for some reasons have to be instantiated in the different modules bootstraps. But in those forms I want to use

$this->setAction($this->getView()->url(array('controller' => 'foo', 'action' => 'bar')));

in the constructor. But since the viewhelper url is not accessible yet since I'm in the bootstrap, is there anyway around this? What I get now is

Fatal error: Uncaught exception 'Zend_Controller_Router_Exception' with message 'Route default is not defined'

on that line. I have NO custom routes so I only use the default router and routes.


Solution

  • I decided to change my approach and made the class that manages all the forms accept strings of forms instead of the forms.

    static public function registerForm($formClassName, $formName) {
      self::$_forms[$formName] = $formClassName;
    }
    

    Then I created function to get a form or all forms from the class like so

      public function getForm($name) {
        if(empty(self::$_forms[$name])) {
          throw new Core_Form_Store_Exception;
        }
        // If the for is instanciated we return it
        else if(self::$_forms[$name] instanceof Zend_Form) {
          return self::$_forms[$name];
        }
        else {
          // Instanciate the class and return it
          $form = new self::$_forms[$name];
          self::$_forms[$name] = $form;
          return $form;
        }
      }
    

    getForms() only calls getForm() for each available form. I tired to mimic the interface of the normal Zend_Form a bit when it comes to the names of functions and the order arguments are passed. Now I have it working and as a bonus I don't actually instantiate any form until I need it. And if I only request a specific form from the store class only that form is instantiate and saved for future access.