Using a helper inside another helper

Published on February 19, 2007 and tagged with cakephp  helper

If you write a helper you sometimes want to access functions of another helper. Let’s say you want to use the link() function of the HtmlHelper in your own helper. First you have to define the helper you want to use in the $helpers array:

class TestHelper extends AppHelper {
    var $helpers = array('Html');
}

You may expect that you could use the helper with $html->link(), but that leads to an “undefined variable” error (I blunder into this trap almost every time I use this functionality *g*). Instead you have to use $this->Html->link() as shown in the example:

class TestHelper extends AppHelper {
    var $helpers = array('Html');

    function getTheLink() {
        return $this->Html->link('The link', '/');
    }
}

6 comments baked

  • Kym January 07, 2009 at 04:07

    Hey thanks so much, I was using it without $this!

  • cakebaker January 07, 2009 at 18:49

    @Kym: You are welcome!

  • Dan July 16, 2009 at 07:45

    Thanks for posting this. It was exactly what I was looking for as I wasn’t quite sure how to access a helper from within a helper.

  • cakebaker July 16, 2009 at 16:05

    @Dan: I’m glad this article was helpful for you, and happy baking!

  • enrique September 14, 2009 at 11:52

    Hi, thanks for the article!

    Is it possible to request a helper inside a helper’s method? Same as you would do in a controller’s action instead of the entire controller?

    function getTheLink() {
    var $helpers[] = ‘Html’;

    return $this->Html->link(‘The link’, ‘/’);
    }

  • cakebaker September 14, 2009 at 17:21

    @enrique: Thanks for your comment!

    You could use something like:

    function getTheLink() {
        App::import('Helper', 'Html');
        $this->Html = new HtmlHelper();
    
        return $this->Html->link('The link', '/');
    }

    And depending on the helper you want to load you have to do some initializations.

    However, if possible, I would avoid this approach and use what I described in the article ;-)

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License