Zend Framework 2 : Create Your Custom View Helper
In MVC Architecture, sometimes, we have to do a “logic” to manage a view. The Logic is called by View named View Helper. Zend Framework 2 has a ton of flexibility, so, we can create a custom View Helper if we want to -that can be called by View Layer over modules.
For Example, i want to create a View Helper named Testhelper which the responsibility of this helper is to state that the string is found or not. First of all, we create a Helper under src directory :
And the content of Testhelper is :
namespace Test\View\Helper; use Zend\View\Helper\AbstractHelper; class Testhelper extends AbstractHelper { public function __invoke($str, $find) { if (! is_string($str)){ return 'must be string'; } if (strpos($str, $find) === false){ return 'not found'; } return 'found'; } }
The next step is register that in Module.php
namespace Test; use Zend\ModuleManager\Feature\AutoloaderProviderInterface, Zend\ModuleManager\Feature\ConfigProviderInterface, Zend\ModuleManager\Feature\ViewHelperProviderInterface; class Module implements AutoloaderProviderInterface, ConfigProviderInterface, ViewHelperProviderInterface { public function getAutoloaderConfig(){/*common code*/} public function getConfig(){ /*common code */ } public function getViewHelperConfig() { return array( 'factories' => array( 'test_helper' => function($sm) { $helper = new View\Helper\Testhelper ; return $helper; } ) ); } }
OR, you can SIMPLIFY that by configuring it as an invokable in module.config.php as @weierophinney ( project lead for Zend Framework ) suggestion –thanks a lot for his suggestion– like this :
return array( //......... 'view_helpers' => array( 'invokables'=> array( 'test_helper' => 'Test\View\Helper\Testhelper' ) ), //......... );
Last step, call it in the view :
echo $this->test_helper("me","e");
Excelent tutorial bro!! I’m learning ZF2 and your site is very good.
Thank you 😉
Great job !
Thank you
You’re welcome 😉
$this->paginationControl($albums, ‘Sliding’, ‘pager.phtml’, array(‘lang’=>’en’)) is not working for me.
$this->pageCount dont have any value
$this->getRequest()->getServer()->get(‘QUERY_STRING’) is not returning anything
Please suggest me
make sure that data was valid for your current paginator adapter used.
its working. thanks a lot.
You’re welcome.
[…] post about creating Controller pLugin in ZF2. For what have to do to create a View Helper , see : my post about creating view helper or EvanDotPro’s […]
Thanks for that and happy new year 🙂
You’re welcome 😉
Hi
I’m trying to create my View Helper where i will create IMG tag
so far i have this:
But i have an error on line with $this->view->escape($value)
and the question is how i can get function escape to work here?
Error message
“Fatal error: Uncaught exception ‘Zend\ServiceManager\Exception\ServiceNotFoundException’ with message ‘Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for escape’ in ”
thx
You should extends
which Escaper is placed., so the code should be :
and use $this->getEscaper()->escapeHtml() to escape the html.
do escapeJs() or other depend on your need.
so, in the view, you can call :
thx its working 😉
You’re welcome 😉
use Zend\ModuleManager\Feature\AutoloaderProviderInterface,
Zend\ModuleManager\Feature\ConfigProviderInterface,
Zend\ModuleManager\Feature\ViewHelperProviderInterface;
class Module implements
AutoloaderProviderInterface,
ConfigProviderInterface,
ViewHelperProviderInterface
{//..
public function getViewHelperConfig()
{
return array(
‘factories’ => array(
‘Ie9’ => function ($sm) {
$locator = $sm->getServiceLocator();
$viewHelper = new View\Helper\Ie9;
return $viewHelper;
}
),
);
}
//…
}
Tanya sedikit mas Iksan, kalo untuk dipakai semua module berarti harus di register di invocables di module.config nya ya?
Apa memungkinkan kalau dibuat di library eksternal, jadi bisa ambil dari situ, tidak perlu register2 lagi.
Trims.
baca deh tentang service manager di sini https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/ baca baik2 di section abstract_factories.
Hi, I tried this but get the following error and my application crashes:
Warning: Class ‘Zend\Stdlib\ArrayObject\PhpReferenceCompatibility’ not found in C:\Program Files (x86)\Zend\ZendServer\data\apps\http\__default__\MT5_0\1.0.0\vendor\zendframework\zendframework\library\Zend\Stdlib\ArrayObject.php on line 24
Fatal error: Class ‘Zend\Stdlib\AbstractArrayObject’ not found in C:\Program Files (x86)\Zend\ZendServer\data\apps\http\__default__\MT5_0\1.0.0\vendor\zendframework\zendframework\library\Zend\Stdlib\ArrayObject.php on line 33
Any Ideas? i really like your tutorials by the way.
use ZendSkeletonApplication to be a skeleton project. clone this : https://github.com/zendframework/ZendSkeletonApplication and update your ZF library to the latest master.
hello samsonasik i want put search box in my form for search data but i’dont get any easy solution for same and also i am new in zend so can you put tutorial step by step for my help..
you can create a form to accomodate it. thanks for the suggestion.
Hello, please advice how to use url() helper in custom view helper. Thank you for your time.
you can do something like this :
Thank you.
you’re welcome 😉
how to add a helper to specified module?
this will apply to all modules ..
‘view_helpers’ => array(
‘invokables’=> array(
‘test_helper’ => ‘Test\View\Helper\Testhelper’
)
),
all module config are merged, and the view helper should only called if that called, there is no concept like you mentioned :p
Good work mate! your expertise and this blog has really been helpful. I just have suggestion if you can put a demo link of the sample code it would be great as people can see the actual working of the code bits. Cheers!
help me!
Database
CREATE TABLE IF NOT EXISTS `Menu` (
`idmenu` int(2) NOT NULL AUTO_INCREMENT,
`NameMenu` varchar(255) NOT NULL,
PRIMARY KEY (`idmenu`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
NSERT INTO `Menu` (`idmenu`, `NameMenu`, ) VALUES
(1, ‘Home’),
(2, ‘Who we are’),
(3, ‘Products’),
(4, ‘Downloads’),
(5, ‘Search’),
(6, ‘Logon’),
(7, ‘Contact us’);
Module
Ema
–config
–module.config.php
–src
–ema\view\helper\
–MenuHelper.php
–view
–layout
–layout.phtml
–Module.php
–autoload_classmap.php
1.File module.config.php
array(
‘invokables’=> array(
‘menus’ => ‘Ema\View\Helper\MenuHelper’,
)
),
);
2.MenuHelper.php
namespace Ema\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\Db\Adapter\Adapter;
class MenuHelper extends AbstractHelper {
Protected $adapter;
public function __construct(Adapter $adapter) {
$this->adapter = $adapter;
}
public function __invoke()
{ $result = $this->adapter->query(‘SELECT * FROM `Menu` ‘);
return $result->toArray(); }
}
3.layout.phtml
$menus as $menu){
?>
error lauoyt.php foreach($this->$menus as $menu)
Database
CREATE TABLE IF NOT EXISTS `Menu` (
`idmenu` int(2) NOT NULL AUTO_INCREMENT,
`NameMenu` varchar(255) NOT NULL,
PRIMARY KEY (`idmenu`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
NSERT INTO `Menu` (`idmenu`, `NameMenu`, ) VALUES
(1, ‘Home’),
(2, ‘Who we are’),
(3, ‘Products’),
(4, ‘Downloads’),
(5, ‘Search’),
(6, ‘Logon’),
(7, ‘Contact us’);
Module
Ema
–config
–module.config.php
–src
–ema\view\helper\
–MenuHelper.php
–view
–layout
–layout.phtml
–Module.php
–autoload_classmap.php
1.File module.config.php
array(
‘invokables’=> array(
‘menus’ => ‘Ema\View\Helper\MenuHelper’,
)
),
);
2.MenuHelper.php
namespace Ema\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\Db\Adapter\Adapter;
class MenuHelper extends AbstractHelper {
Protected $adapter;
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
}
public function __invoke()
{
$result = $this->adapter->query(‘SELECT * FROM `Menu` ‘);
return $result->toArray();
}
}
3.layout.phtml
$menus as $menu){
?>
hi
I am trying to do navigation with menu and sub menu but not getting……Could you please help me
[…] Weißt du denn, wie eigene View-Helper eingebunden werden? Ansonsten verweise ich einfach mal auf Zend Framework 2 : Create Your Custom View Helper | Welcome to Abdul Malik Ikhsan's Blog An die __invoke-Methode übergibst du dann die Formular-Elemente. In dieser baust du dann einfach […]
Great tutorial! One question: How to get the translator working / conform inside a view helper? Possible?
you can call $this->view->viewhelpername() inside the view helper class.
Thanks for your really quick reply :-). Sorry, maybe my question was not good.
How can i use the translator->translate(); within a view helper to translate some needed strings? And does it has an impact on the performance if I se the translator inside a view helper.
call via :
inside view helper.
You’re the best! Thanks a lot! Now I’m even more think that the ZF2 is really awesome. Getting more and more comfortable with it. And still a lot to learn and discover :-).
you’re welcome 🙂
Hello samsonasik,
Thanks for sharing this grate tutorial. Can I make multiple function in Testhelper.php file like sortString,uppercase,lowercase etc. If It is possible then how will I use.
Thanks in advenced.
ofcourse, as far as the access modifier of that function is public. you can do
How to define and access multiple function from one helper class
test_helper->calculatetotal(20);
$this->test_helper->calculatearea(30);
Thanks in advance for reply 🙂
class Testhelper extends AbstractHelper
{
public $sum;
public function __invoke()
{
return $this;
}
public function calculatetotal($sum)
{
return $sum+$sum;
}
public function calculatearea($sum)
{
return $sum*$sum;
}
}
$this->test_helper()->calculatearea(30);
you missed () to get the __invoke()/__construct() function first.
Thanks got it 🙂
$this->test_helper()->setUserName(‘test’)
thank so much!
I’m having problems trying to create my own FormRow based on Zend2 with just few changes on how render create the layout and where errors are placed. I’ve created my own FormRow class, adding this class to invokables
public function getViewHelperConfig()
{
return array(
‘invokables’ => array(‘formelementerrors’ => ‘Events\Form\View\Helper\FormElementErrors’,
‘formrow’ => ‘Events\Form\View\Helper\FormRow’),
);
But getting this error and I’m a little bit lost. Can you give me a little bit of your zend2 wisdom to guide me?
Argument 1 passed toXXXXX\\FormRow::render() must be an instance of Events\\Form\\View\\Helper\\ElementInterface, instance of Zend\\Form\\Element\\Select given, called in XXXX/vendor/zendframework/zendframework/library/Zend/Form/View/Helper/FormRow.php on line 107
Thanks
[…] post about creating Controller pLugin in ZF2. For what have to do to create a View Helper , see : my post about creating view helper or EvanDotPro’s […]
Hi,
I would like to create view helper for setting attributes for select options
For example
128 x 128
64 x 64
This width & height attribute would be set on runtime.
Plz Help
Sorry
the example is as
128 x 128
64 x 64
Sorry for posting this replies multiple times…….
you can extends ZF2 FormSelect view helper https://github.com/zendframework/zf2/blob/master/library/Zend/Form/View/Helper/FormSelect.php and modify the behaviour for your need.
Reblogged this on Flavio's Blog and commented:
Ejemplo para crear Views Helpers en ZF2
Om, mau tanya.. kalau mau buat fungsi tanggal, hari ,bulan versi Indonesia, harus pake view helper kah om??
boleh kasih sedikit tips ga sama ane.. masih baru belajar om… 🙂
Makasih banyak om…
ya, bisa buat view helper sendiri. contohnya, buat aja class seperti ini https://samsonasik.wordpress.com/2009/07/24/membuat-library-sendiri-di-zend-1-8-4/ tapi dibuat zf2 view helper . contoh buat view helper bisa baca di sini https://samsonasik.wordpress.com/2012/07/20/zend-framework-2-create-your-custom-view-helper/
Makasih banyak om… Jaya terus om…
sip, Aamiin 🙂
Hello Samsonasik,
I need your help .
I want to show some data from model to footer.phtml/layout.phtml .
I am trying it with custom view helper but there is problem of database connectivity .
is there another way to do this .
If i seprate header.phtml ,footer.phtml and menu.phtml and want to some data module wise then how shoild i approach please help.
Thanks. It is works for me.
[…] https://samsonasik.wordpress.com/2012/07/20/zend-framework-2-create-your-custom-view-helper/ […]
I am trying to create a custom view helper in zf2 for testing
I created it as below…
inside Application\Application\View\Helper\LiveStreaming.php
inside Application\Module.php
array(
‘liveStreaming’ => function($name) {
return new View\Helper\LiveStreaming($name);
},
),
);
}
?>
Now I am calling that view inside different model call News
News\view\news\news\index.phtml
liveStreaming(‘Ivan Gospodinow’); ?>
its not giving any response. Can you please tell me where I am doing mistake. I have checked almost all your post example, but not getting my answer.
Thank you in advance.
please re-read my posts, the service must be registered under ‘factories’ or ‘invokables’ or ‘abstract_factories’ or ‘services’, etc. please read https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/ ,also, please read the docs http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.advanced-usage.html#zend-view-helpers-advanced-usage
thank you samsonasik. very nice it’s very helpful to me
Hi samsonasik , first thanks for the tuto ,
it worked perfectly with one viewHelper , plz how can we add an other view helper and add declare it in the Module.php under factories , i tried my best but can’t get it ….
public function getViewHelperConfig()
{
return array(
‘factories’ => array(
‘test_helper’ => function($sm) {
$helper = new View\Helper\Testhelper ;
return $helper;
}
)
);
}
add more view helper in different key with different name
is it like this :
return array(
‘factories’ => array(
test_helper=> function() {
$helper = new View\Helper\Testhelper () ;
return $helper;
},
‘enabling’ => function() {
$helper = new View\Helper\Enabling ();
return $helper;
},
)
);
waiting for your answer … thanks
that should work, but remember that if you don’t need dependency when creating an instance, you don’t need factories, use invokables instead, read https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/
yeah , it works …. i know that there ‘s two ways to declare view helpers in ZF2 under invokables and factories.
thanks a lot
you’re welcome 😉
Hey,
I need to access session from main layout file. please suggest
use view helper for that http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.identity.html , for specific usage, create your own, read servicemanager cheat sheet https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/
Can I use a variable in ViewModel array in view helper also like I use in view $this->someVariableFromController? If No then how.
view helper is not intended to grab viewHelper variable, if you need, you could just pass the variable to view helper method. $viewhelper->method($viewModelVariables); and proceed inside the method body.
I learn a lot from your blog. Very good
Very Thanks!!!!!!!!!!!!!!!!!!!!!!! ‘-‘
You’re the best bro!
Thanks a lot for all your tutorials.
They really help me
great !:)
Grt Job 😀
As per this code helper is used for particular module. Is it possible global helper for all module or helper in autoload like Codeiigniter.
you can use anywhere in any module
Trank you for made this example (Y)
[…] https://samsonasik.wordpress.com/2012/07/20/zend-framework-2-create-your-custom-view-helper/ […]