1
votes

I created my own helper on CakePHP 2.x that uses the HtmlHelper but it doesn't work, here is the code

class NavHelper extends Helper {

   public $helpers = array("Html", "Javascript");

   function __construct($config = array()) {

}

function link($label, $options) {
    if($this->perms(array('controller'=>$options['controller'],'action'=>$options['action']))) {
        $html = '<a ';
        foreach($options as $label => $value) {
            if($label != 'action' || $label != 'controller') {
                $html .= " {$label}=\"{$value}\" ";
            }
            $html .= " href='".$this->Html->url(array('controller'=>$options['controller'],'action'=>$options['action']))."'>".$label."</a>";
        }

        return $html;
    }
    return '';
}

Fatal error: Call to a member function url() on a non-object in C:\Bitnami\wappstack-5.5.28-0\apache2\htdocs\pokeadmin_v2\app\View\Helper\NavHelper.php on line 17

But $this->Html->url worked perfectly on CakePHP 1.3 but on CakePHP 2.x won't work, also tried to use $this->Html = new HtmlHelper; with the following error:

Warning (4096): Argument 1 passed to HtmlHelper::__construct() must be an instance of View, none given, called in C:\Bitnami\wappstack-5.5.28-0\apache2\htdocs\pokeadmin_v2\app\View\Helper\NavHelper.php on line 11 and defined [CORE\Cake\View\Helper\HtmlHelper.php, line 161

I also checked the documentation but no luck.

3

3 Answers

1
votes

You broke the constructor, in two ways that is, first it doesn't accept the arguments required by its parent (view and configuration), and it also never invokes the parent, which is where the required helper map is initialized.

If you don't need the constructor, don't override it, and if you do, make sure that you accept the required arguments and that you pass them on to the parent constructor.

public function __construct(View $view, $settings = array()) {
    parent::__construct($view, $settings);
    // ...
}

See also Cookbook > Views > Helpers > Using and Configuring Helpers

0
votes

Just found that i can use Router::url for the same action as $this->Html->url

0
votes

This might be a bit off subject, but it might help someone new to CakePHP who happens to stumble across this on here;

You can load Helpers directly on the AppController as such:

namespace PluginName\Controller;

use App\Controller\AppController as BaseController;
use Cake\Http\Response;
use Cake\Http\ServerRequest;

class AppController extends BaseController
{
    public $helpers = ['PluginName.HelperName'];

    // ....
}

Reference: https://book.cakephp.org/3.0/en/views/helpers.html#loading-helpers-on-the-fly