0

I'm trying to use a rendered view in a JSON object and then return this to the client. How can I render a phtml file that doesn't really belong to specific action?

The requested action from the client has no view. It then calls prepareForm(). Inside this function i want to render form.phtml and pass the output to the 'html' key of the array.

private function prepareForm()
    {
        $json = Zend_Json::encode(array(
            'html' => $this->partial('form.phtml'),
            'role' => $this->role,
            'lang' => $this->lang
        ));

        echo $json;
    }

How can I do this in the Zend Framework? What's the best way to do this?

Many thanks

2 Answers 2

1

You need an Zend View instance:

private function prepareForm()
{
    $view = new Zend_View();
    $path = '/../'; // Replace with path to phtml

    $view->addScriptPath($path);

    $json = Zend_Json::encode(array(
        'html' => $view->render('form.phtml'),
        'role' => $this->role,
        'lang' => $this->lang
    ));

    echo $json;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can disable the layout and view using in your action:

$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();

To me, echo from controllers is not the right way to do things. The MVC pattern is used to separate logic to view. You can just disable the layout and assign to your view the json to render as follow:

$this->view->json = $json;

and in your view:

<?= $this->json ?>

If your request comes from an Ajax script, you can even makes things prettier using the AjaxContext action helper. This will allow you to use one action for different kind of request for example, and render the right view according to the request type (Ajax, etc).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.