ceadreak
ceadreak

Reputation: 1684

How to render a view in modal window using ajax in ZF2?

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?

Upvotes: 1

Views: 2557

Answers (3)

M.Prasath
M.Prasath

Reputation: 1

Have the same problem this works...

$.get("<?php echo $this->url('your url'); ?>", function(data) 
{
    console.log(data);
    $('#myModal .modal-body').html(data);
});

Upvotes: 0

ceadreak
ceadreak

Reputation: 1684

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

Upvotes: 1

edigu
edigu

Reputation: 10099

All you need is disabling the layout using setTerminal() and returning proper model from your controller to render HTML output in your modal.

In your case, you have to return a ViewModel instance. So, your first approach is correct. This should work:

$htmlViewPart = new ViewModel();
$htmlViewPart->setTemplate('path/to/my/view')
             ->setTerminal(true)
             ->setVariables(['arrayVar' => ['a', 'b', 'c']]);

return $htmlViewPart;

The second case is; you're trying to use a HTML output as json data. Try to change your ajax loading mechanism similar to this:

$(".my-modal-link").click(function() {
    $.get("/url/to/my/action", function(data) {
        $('#myModal .modal-body').html(data);
    });
});

This will be append the rendered output (which doesnt have a layout) into modal's body. You may also want to read this for JsonModel scenario.

Hope it helps.

Upvotes: 1

Related Questions