Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a page in zend framework 2?

I used below code to render a page in the controller action.

public function userinforeceiveAction()
{   
    $renderer = new PhpRenderer();

    $map = new Resolver\TemplateMapResolver(array(
    'userinfo' => __DIR__ . '/userinfo.phtml',
        ));

        $resolver = new Resolver\TemplateMapResolver($map);
        $renderer->setResolver($resolver);
        $model = new ViewModel();
        $model->setTemplate('userinfo');

        return new ViewModel();    
}

and I echo rendering content in the view.

echo $renderer->render($model);

but it render nothing. Please help me. thanks. and also its fine work with zf1 by this two lines.

$this->userinfoAction();
$this->$render('userinfo');
like image 953
Mangala Edirisinghe Avatar asked Dec 16 '22 00:12

Mangala Edirisinghe


2 Answers

If you are using the ZF2 MVC layer you don't need to instantiate your own view rendering, just return a ViewModel instance and it will take care of the rest:

public function userinforeceiveAction()
{
    $vm = new ViewModel();
    $vm->setTemplate('userinfo');
    return $vm;
}

For an example of how to use view models see Akrabat's ZF2TestApp: http://zf2test.akrabat.com/

The associated ZF2 code is linked at the bottom of that page and the template map is configured in the module configuration file

like image 185
Adam Lundrigan Avatar answered Dec 21 '22 11:12

Adam Lundrigan


Actually what you have done should work with following miner changes

public function userinforeceiveAction()
{   
    $renderer = new PhpRenderer();

    $map = new Resolver\TemplateMapResolver(array(
    // first mistake
    // __DIR__ is the directory of application controller, not the path of views 
    // second mistake
    // 'userinfo' should be '(controller)/(action)'
    'userinfo' => __DIR__ . '/userinfo.phtml',
        ));

        // third mistake
        // since $map is a resolver instance, this is wrong
        $resolver = new Resolver\TemplateMapResolver($map); // no need
        $renderer->setResolver($resolver);
        // should be $renderer->setResolver($map);
        $model = new ViewModel();
        // 'userinfo' should be changed
        $model->setTemplate('userinfo');

        // big mistake
        // what you are returning here is new instance of view model
        return new ViewModel();
        // instead you should return $model 
}

No need of this line within the view

echo $renderer->render($model);

But the best and recommended way is to inject through the module configuration file, as Adam said

The documentation will provide better explanation

like image 44
code-jaff Avatar answered Dec 21 '22 09:12

code-jaff