Platform: Zend Framework 2
Objective: from a controller send an email using Zend/View for the email body
In every day practice Zend\View is called inside a controller action, some variables are passed through the constructor, a template is set and then the view model is returned. The rendering of the view is taken care of. But what if you do not want to render the view immediately but want to capture the output? The code snippet below demonstrates how to use the view model for generating an email body:
$mail = new Zend\Mail\Message; $bodyPart = new Zend\Mime\Message; $viewModel = new ViewModel(); $viewModel->setVariable('param', array()); $viewModel->setTemplate('send/mail'); $renderer = new \Zend\View\Renderer\PhpRenderer; $resolver = new \Zend\View\Resolver\AggregateResolver(); $map = new \Zend\View\Resolver\TemplateMapResolver(array( 'send/mail' => __DIR__ . '/../../../view/application/send/mail.phtml', )); $resolver->attach($map); $renderer->setResolver($resolver); $mailBody = $renderer->render($viewModel); $htmlPart = new Zend\Mime\Part($mailBody); $htmlPart->type = 'text/plain'; $bodyPart->setParts(array($htmlPart)); $mail->setBody($bodyPart); $mail->setFrom($from, $fromName); $mail->addTo($to); $mail->setSubject('Greetings'); $transport = new \Zend\Mail\Transport\Sendmail(); $transport->send($mail);
Basically a renderer is required to capture the view which in turn requires a resolver to the find the template file. That is where the map comes in. This last bit is counter-intuitive because a view manager configuration has already been set in the module config.
is just not going to work.
Of course the are several renderers and several resolvers to choose from, adding to the challenge.
In ZF1 a view script can also be rendered to a variable:
$this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $text = $this->view->render('account/view.phtml');
Check if the correct script paths exist with $this->view->getScriptPaths()