I try to render an action with a dedicated view in a modal window with an ajax call in Zend Framework 2.
This is my controller action :
public function myAction()
{
$htmlViewPart = new ViewModel();
$htmlViewPart->setTemplate('path/to/my/view')
->setTerminal(true)
->setVariables(['arrayVar' => ['a', 'b', 'c']]);
return $htmlViewPart;
}
The view :
<?php
foreach($arrayVar as $k => $v)
{
echo $k . ':' . $v . '<br>';
}
The js :
$(".my-modal-link").click(function() {
$('#myModal .modal-body').load($(this).data('/url/to/my/action'));
});
This not do the trick. I also tried with a JSON model too:
public function myAction()
{
$htmlViewPart = new ViewModel();
$htmlViewPart->setTemplate('path/to/my/view')
->setTerminal(true)
->setVariables(['arrayVar' => ['a', 'b', 'c']]);
$htmlOutput = $this->getServiceLocator()->get('viewrenderer')->render($htmlViewPart);
$jsonModel = new JsonModel();
$jsonModel->setVariables(['html' => $htmlOutput]);
return $jsonModel;
}
But the final render in the modal is something like :
{"html":"0:a\u003Cbr\u003E1:b\u003Cbr\u003E2:c\u003Cbr\u003E"}
Have an idea to how achieve that?
I found a solution.
Just create an empty layout returning content.
// Application/view/layout/ajax.phtml
<?php
echo $this->content;
And set this template in the action view
<?php
$this->layout()->setTemplate('layout/ajax');
It works now with Jquery $.load() / ViewModel strategy