Search code examples
phpzend-framework2zend-view

zend error while assigning view


So installed the latest 2.0 version of Zend. I am having trouble in defining the view in controller and then displaying. If I create a new ViewModel and return it, it works fine. For example.

public function __construct()
    {
        $this->view = new ViewModel();
    }

$this->view->hello="hey";
$this->view->test="there";
return $this->view;

But I never had to do this in Zend 1.8 or before. Without creating a new model, it gives me the following error:

Strict Standards: Creating default object from empty value in /path-to-controller-file.php

Do I Have to set it somewhere else?


Solution

  • ZF2 is vastly different from the previous versions of Zend Framework, so you'll probably run into a few issues like this.

    The error you are encountering is because $this->view would be null without the new ViewModel() and therefore setting further variables on a null is triggering that error. From my understanding of ZF2 - the view and controller have been purposely separated.

    Typically in ZF2 you return data from an action doing:

    $viewModel = new ViewModel();
    $viewModel->hello = 'hey';
    
    return $viewModel;
    

    You can also return an array if I remember correctly:

    return array('hello' => 'hey');