Adding Custom View Helper In Zend Framework 2

September 30, 2012

Here is example implementation of a custom view helper script.

Step 1.

Creating Zend Framework 2 Helper.

//file : App_folder/module/Module_name/src/Module_name/View/Helper/SayHello.php

namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;

class SayHello extends AbstractHelper{

	public function __invoke($name = 'Unnamed'){
		return "$name , this is Zend Framework 2 View Helper";
	}
}

Step 2.

Registering the Zend Framework 2 Helper.

//file : App_folder/module/Module_name/Module.php

 public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
                // the array key is the name of the invoke function that is called from view
                'sayHello' => function($name) {
                    return new SayHello($name);
                },
            ),
        );
    }

Step 3.

Using in Zend Framework 2 View.

//file : App_folder/module/Module_name/view/Module_name/index/index.phtml

 echo $this->sayHello('Ivan Gospodinow');

 

Suggestions or problems ?

Write a comment.

tags: ,
posted in how to ?, Zend Framework 2 by Ivan Gospodinow

Follow comments via the RSS Feed | Leave a comment | Trackback URL

5 Comments to "Adding Custom View Helper In Zend Framework 2"

  1. anil wrote:

    Hi

    I am unable to call this view form phtml file

  2. Ivan Gospodinow wrote:

    Hello anil,

    can you be a litthe more specific because I can not understand what is the problem.

  3. Phil wrote:

    Line 3 needs an echo statement for it to display anything 🙂

    echo $this->sayHello(‘Ivan Gospodinow’);

  4. Joseph wrote:

    I did a small change in the step 2:

    return new View\Helper\GetSiteUrl();

    It works fine after that for me.

    Thank you for your great post.

  5. King wrote:

    Can I pass back a partial or a file with php and html from invoke?

Leave Your Comment


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/c2kblate/sites/ivangospodinow.com/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org