Search code examples
phpzend-frameworklayoutmodulecontrollers

Zend Framework: Multiple Modules in layout


How can I have multiple actions in my layout from different controllers/modules?

I tried this:

<div id="login"><?php $x=new User_LoginController; $x->LoginAction() ?>

<div id="news"><?php $x=new Site_NewsController; $x->ShowAction() ?>

Solution

  • You'll want to implement view helpers, specifically the placeholder() view helper.

    For example to render a login form in any or all pages of your application, we start with a placholder for the form in our layout or view script:

    <!--layout.phtml-->
    <div>
        <?php echo $this->layout()->login . "\n"?>
    </div>
    

    I use an action helper to prepare the form for display:

    <?php
    
    /**
     * Prepares login form for display
     */
    class My_Controller_Action_Helper_Login extends Zend_Controller_Action_Helper_Abstract
    {
    
        /**
         * @return \Application_Form_Login
         */
        public function direct()
        {
            $form = new Application_Form_Login();
            //this is the url of the action this form will default too
            $form->setAction('/index/login');
    
            return $form;
        }
    }
    

    now from any controller or front controller plugin the placeholder can be setup:

    public function preDispatch()
        {
            $this->_helper->layout()->login = $this->_helper->login();
        }
    

    now the login form will display in any action from this controller that uses layout.phtml as it's layout. I'll let you discover plugins yourself.

    Using helpers with placeholders would usually be the prefered way to accomplish what you want. However if you absolutely must display an action inside of anothers view you can use the Action view helper, just be aware that performance may suffer.

    <div id="login">
         <?php echo $this->action('login', 'login', 'user'); ?>
    </div>