Wednesday 30 December 2015

Zend Framework2 manage layout and view variables from controller

Zend Framework manage layout and view variables from view


Question: How to set variable to layout from controller?
Following are different three ways to set the variable from controller.
First way
public function indexAction(){ 
    $this->layout()->variableName = 'value1';
}

Second way
public function indexAction(){ 
    $this->layout()->setVariable('variableName', 'value2');
}

Third way
    public function indexAction(){ 
    $this->layout()->setVariables(array(
        'variableName1' => 'value1',
        'variableName2'  => 'value2',
    );
}

In layout File, you can access with following way.
$this->variableName1;


Question: How to set variable to view from controller in Zend Framework2
public function indexAction(){ 
return new ViewModel(array(
           'variableName3' => 'value 3',
         ));
}

in layout view, you can access with following way.
$this->$this->variableName2;



Question: How I can get access to my module config from the controller?
public function indexAction(){ 
    $config = $this->getServiceLocator()->get('Config');
}



Question: How to Change layout in the controller in Zend Framework 2.0?
public function indexAction(){ 
    $this->layout('layout/mynewlayout'); /*It will search view/layout/mynewlayout.phtml*/
}



Question: How to disable layout in zend framework 2?
public function indexAction(){ 
    $viewModel = new ViewModel();
    $viewModel->setTerminal(true);
}



Question: How to disable render view in zend framework 2?
public function indexAction()
{ 
    return false;
}