Zend Framework Custom View Helper

Zend Framework Custom View Helper

Creating custom helper in new Zend Framework edition 1.9 in few easy steps.
Let’s assume that we need to fetch some data from database
but we do not need them in all view files.

We need to insert this line in application/config.ini to register path to helpers:

application/configs/application.ini
resources.view.helperPath = APPLICATION_PATH “/views/helpers”

First create model which will give you an array,
in my example it’s list of states, which you will call in you helper file:

application/models/DbTable/States.php

class Model_DbTable_States extends Zend_Db_Table_Abstract
{
protected $_name = 'state_list';
 
public function getStates()
{
 
$row = $this->fetchAll();
if (!$row) {
throw new Exception("No States");
}
 
$row = $row->toArray();
 
return $row;
}
}

Class needs to begegins with “Zend_View_Helper_”
That is why it is “view helper” and it cannot be called in controller or model files,
if you do that you will get error that “method deoesn’t exists”.

application/view/helpers/State.php

class Zend_View_Helper_State
{
protected $_list;
 
public function state()
{
$state = new Model_DbTable_States();
return $this->_list->getStates();
 
}
}

After that and make a list of states in:

application/layouts/sidebar.phtml

<ul>
 	<li style="list-style-type: none;">
<ul>< ?php foreach ($this->state() as $item):?>
 	<li>< ?php echo $item['state']?></li>
</ul>
</li>
</ul>
< ?php endforeach;?>

and call it in main layout file:

application/layouts/layout.phtml

< ?php echo $this->partial('sidebar.phtml');
?>

In this case you will get content from your helper file in all views which will render main layout file from application/layouts/layout.phtml.
However, if you wish to call your helper in particular view all you need to do is to call the helper in view file:

< ?php $this->state();
?>

You made it all the way down here so you must have enjoyed this post! You may also like:

Reorder input fields on Shipping and Billing step in Magento 2 Mladen Ristic
, | 14

Reorder input fields on Shipping and Billing step in Magento 2

More/Less functionality in Magento2 Danijel Vrgoc
, | 6

More/Less functionality in Magento2

ZendFramework example on using Google URL Shortener service Branko Ajzele
Branko Ajzele, | 3

ZendFramework example on using Google URL Shortener service

23 comments

  1. Suppose I have two helpers and both have function state(). How can we call this function for a particular class?

  2. Thanks a lot!
    You may use another Helper-Prefix for your class, e.g. Application_View_Helper instead of Zend_View_Helper, if you use in your application.ini:

    1. thanks for the good tutorials, I hope you can help me with the below:

      I built a custom view helper to display a login/registration view script with forms site-wide, for convenience I just call the custom view helper from the layout like $this->loginRegister().

      However I found it very complex to get access to the ZF2 standard view helpers using this method, I had to manually configure it to get access to the form helpers and now I have another problem, the url helper ($this->url(); ?> is also not available in my view script, or something else is wrong because I get the error ‘Zend\View\Exception\RuntimeException’ with message ‘No RouteStackInterface instance provided’

      Sorry for pasting my code here but please tell me if this is the wrong approach because to me it looks really overly complex and I hope there is a simpler way to accomplish this.

      public function __invoke()
      {
      
      $userForm = new \SgUser\Form\UserMinimal();
      $logInForm = new \A8Auth\Form\LogIn();
      
      $renderer = new \Zend\View\Renderer\PhpRenderer();
      $resolver = new \Zend\View\Resolver\TemplateMapResolver();
      $resolver->setMap([
      'sg_register_minimal' => SG_FRONT_TEMPLATE_DIR . '/partial/login-register-minimal-modal.phtml'
      ]);
      $renderer->setResolver($resolver);
      
      //the standard ZF2 view and form helpers not available to the view model be default, so we configure it here
      
      $plugins = $renderer->getHelperPluginManager();
      $config = new \Zend\Form\View\HelperConfig();
      $config->configureServiceManager($plugins);
      
      $viewModel = new \Zend\View\Model\ViewModel();
      $viewModel->
      $viewModel->setTemplate(‘sg_register_minimal’)
      ->setVariables([
      'registerForm' => $userForm,
      'logInForm' => $logInForm
      ]);
      
      //return the rendered view script
      return $renderer->render($viewModel);
      }
  3. Thanks a lot!
    You may use another Helper-Prefix for your class, e.g. Application_View_Helper instead of Zend_View_Helper, if you use in your application.ini:

    resources.view.helperPath.Application_View_Helper = APPLICATION_PATH "/views/helpers/"
  4. Thank you very much for your post!
    I have just a little question.
    How can I call “sidebar.phtml” in a my view?
    This way “echo $this->partial(‘sidebar.phtml’);” works only in the main layout.phtml and not in a simple view.
    🙂

  5. Thank you for this post. Very simple and to the point and really helped me get over a problem I was encountering while developing one View Helper 🙂

  6. Hi, Iam also getting the above type error, also I written the code for extends the abstract class

    This is my error , please help us.

    Fatal error: Uncaught exception ‘Zend_Loader_PluginLoader_Exception’ with message ‘Plugin by name ‘GetMenus’ was not found in the registry; used paths: Zend_View_Helper_: Zend/View/Helper/;C:\xampp\htdocs\directions\application/views/helpers/;C:/xampp/htdocs/directions/application/views\helpers/’ in C:\xampp\php\PEAR\Zend\Loader\PluginLoader.php:412 Stack trace: #0 C:\xampp\php\PEAR\Zend\View\Abstract.php(1182): Zend_Loader_PluginLoader->load(‘GetMenus’) #1 C:\xampp\php\PEAR\Zend\View\Abstract.php(618): Zend_View_Abstract->_getPlugin(‘helper’, ‘getMenus’) #2 C:\xampp\php\PEAR\Zend\View\Abstract.php(344): Zend_View_Abstract->getHelper(‘getMenus’) #3 [internal function]: Zend_View_Abstract->__call(‘getMenus’, Array) #4 C:\xampp\htdocs\directions\application\layouts\scripts\sidebar.phtml(1): Zend_View->getMenus() #5 C:\xampp\php\PEAR\Zend\View.php(108): include(‘C:\xampp\htdocs…’) #6 C:\xampp\php\PEAR\Zend\View\Abstract.php(888): Zend_View->_run(‘C:\xampp\htdocs…’) #7 C:\xampp\php\PEAR\Zend\View\Helper\Partial.php(105): in C:\xampp\php\PEAR\Zend\Controller\Plugin\Broker.php on line 336

  7. This may solve simple problems but it is not following the MVC pattern and will be a mess if this method is used in larger projects.

  8. I got an error very strange.
    My view helpers have no problem in the views scripts but I cannot call them from my layout scripts.
    Look at my stack:

    Fatal error: Uncaught exception ‘Zend_Loader_PluginLoader_Exception’ with message ‘Plugin by name ‘IsLogged’ was not found in the registry; used paths: Zend_View_Helper_: Zend/View/Helper/’ in /usr/local/zend/share/ZendFramework/library/Zend/Loader/PluginLoader.php:412 Stack trace:
    #0 /usr/local/zend/share/ZendFramework/library/Zend/View/Abstract.php(1174): Zend_Loader_PluginLoader->load(‘IsLogged’)
    #1 /usr/local/zend/share/ZendFramework/library/Zend/View/Abstract.php(610): Zend_View_Abstract->_getPlugin(‘helper’, ‘isLogged’)
    #2 /usr/local/zend/share/ZendFramework/library/Zend/View/Abstract.php(336): Zend_View_Abstract->getHelper(‘isLogged’)
    #3 /Users/gullo/Sites/myproject/application/views/scripts/header.phtml(3): Zend_View_Abstract->__call(‘isLogged’, Array)
    #4 /Users/gullo/Sites/myproject/application/views/scripts/header.phtml(3): Zend_View->isLogged()
    #5 /usr/local/zend/share/ZendFramework/library/Zend/View.php(108): include(‘/Users/gullo/Si…’)
    #6 /usr/local/zend/share/ZendFramework/library/Zend/View/Abstract.php(880) in /usr/local/zend/share/ZendFramework/library/Zend/Loader/PluginLoader.php on line 412

  9. I expect in the solution in file
    application/view/helpers/State.php on line 7
    should be

    $this->_list = new Model_DbTable_States();

    am I right?

  10. Ah, WordPress. The savior and bane of so many.

    Anyway, once I removed the double quotes it was what I needed 🙂

  11. @Jake Noble

    yea, I’m also mad at “Windows OS double quotes” when I used to copy-paste other’s people free code samples..

    But this is something that WordPress does and I’m not supposed to take care of “Windows OS double quotes”

  12. @vedran This line which is not marked as code in your example

    resources.view.helperPath = APPLICATION_PATH “/views/helpers”

    This line is code even if it’s not in code tags, it’s useful. I found this page after Googling for an effective way of adding view helper directories to an app.

    Food that isn’t on a plate is still food?

  13. @Jake Noble

    Form post text or from code sample?

    I just don’t see the issue here,
    part you need is code sample which work on all platforms.

  14. Please Please take the Windows OS double quotes out of your post! People – like me – will spend hours trying to wonder what is wrong, then give up and never use your solution.

  15. Congrats! You were the only one on the whole internet who could explain this in plain english. Come on all you ZF people out there and follow this example 😉

  16. Well yes and no IMHO.
    The controller’s job is to service the request.
    When that logic has nothing to do with some other part of a page then there is no need to complicate your controllers doing stuff that maybe belongs more to the view or layout, than the request itself.
    The controller needs to control what should be under its control – the request.
    But the view should only be accessing data for read purposes in that case, not for writing, and there is one danger – a proxy object would make it safer to do this kind of thing so the view is not given full update access to the model.
    Current thinking seems to be that one way to organise this kind of view+model oriented logic is to have a service layer or service class as a kind of middleware I guess, that can dispense aspects of the model to views (or helpers), and also helps to abstract the ORM stuff.
    But its not in the ZF yet of course.
    So having said that, I would agree that when there is data that is directly involved with the request per se, then first there should be a conversation between the controller and the model and the view should wait patiently until that is done.

  17. I dont think that is a valid MVC aproach to fetch model in the view helper. This is the task of application logic – controllers. After you can wrap data using view helpers.

  18. great great tip, unfortunately I’ve get here after I’ve spent few hours on searching how this should be done.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.