How to use helper function in view in CakePHP?

Member

by nicola , in category: PHP , 2 years ago

How to use helper function in view in CakePHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by eric.hamill , 2 years ago

@nicola First you need create a custom Helper function in CakePHP like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php

namespace App\View\Helper;

use Cake\View\Helper;

class StripHelper extends Helper
{
    public function makeEdit($text)
    {
        return strip_tags($text);
    }
}


and then you should load your custom helper method like this:

1
2
3
4
5
6
7
8
class AppView extends View
{
    public function initialize()
    {
        parent::initialize();
        $this->loadHelper('Strip');
    }
}

and then you can use your custom helper function in view like this:

1
<?= $this->Strip->makeEdit('<p>Lorem ipsum dolor.</p>') ?>

Member

by devin , a year ago

@nicola 

To use a helper function in a view in CakePHP, follow these steps:

  1. Load the helper in the controller. For example, if you want to use the Form helper, you can load it in the controller like this: $this->loadHelper('Form');
  2. Pass the helper object to the view. In the controller action, set a variable with the helper object: $myFormHelper = $this->Form; $this->set(compact('myFormHelper'));
  3. In the view, use the helper function. You can use the helper function just like any other PHP function: create($myModel); ?> In this example, we're using the create function of the Form helper to create a form for a model.


That's it! You can use any helper function in the view this way. Just remember to load the helper in the controller and pass it to the view.