Matthieu Napoli
Matthieu Napoli

Reputation: 49533

Use view helpers in controllers in Zend Framework

I have a controller that is called with AJAX (sends JSON data), so I don't use a view.

I need to use a personnal view helper to format my data, but in my controller.

Is that possible ?

Or maybe I am doing it wrong (maybe I should have a view, but how with JSON) ?

Upvotes: 19

Views: 28565

Answers (5)

David Weinraub
David Weinraub

Reputation: 14184

Another approach is to use the ContextSwitch or AjaxContext action-helpers. This allows you to use a view-script from which you can then call your view-helper in the standard manner.

Upvotes: 1

kindaian
kindaian

Reputation: 51

Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view');

Just be sure that the returned view is the view you want. Because down the line, the view may get overwritten and on the controller you have a spank new view.

And all those values you setup on the view on the action helper and the like... before the controller is kicked in? All gone with the wind!

So test before assuming that if you get a view resource. it is really the same view resource you expect, and that all your vars are still there.

You may be surprised as i was!

Upvotes: 5

Danilo
Danilo

Reputation: 47

You can create an instance of a Helper .. this will work in Controllers, Models and everywhere you need the Helper.

eg.

// create Instance   
$serverUrl_helper = new Zend_View_Helper_ServerUrl();

// get the ServerUrl
$serverUrl = $serverUrl_helper->serverUrl();

Upvotes: 3

takeshin
takeshin

Reputation: 50638

Just use action helpers, many of view helpers are available as action helpers too.

Or directly by using Zend_Date or sprintf.

Upvotes: 0

Gordon
Gordon

Reputation: 316939

You can access any ViewHelper from the Controller by

$this->view->helpername(/*params*/);
// or
$helper = $this->view->getHelper('helpername');
// or
$broker = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$broker->getView()->helpername(/*params*/);

See Zend: How to use a custom function from a view helper in the controller?

However, you might be right that you are doing it wrong (funny pic btw), but I cannot really tell from your question. Please refine it as to why you need to call the view helper and what it is supposed to format.

Upvotes: 45

Related Questions