1

In my CakePHP3.6 project I use the TreeHelper to create my menu.

In my view (pages/index.ctp) I use:

<?=$this->Tree->generate($pages,['alias'=>'title']); ?>

Which creates a basic unordend list.

With TreeHelper I can use a callback function to change the value inside the list items:

<?
$this->Tree->generate($pages,['alias'=>'title','callback'=>'myFunction']);
function myFunction($obj) {
    $id = $obj['data']['id'];

    $return = $this->Html->link('Edit',['action' => 'edit', $id]);
    $return .= $obj['data']['title'];

    return $return;
}
?>

I want to use the HtmlHelper (ie $this->Html->link) to create links, but it gives me this error:

Using $this when not in object context

Is there a solution/ workaround so I can use the HtmlHelper inside the function?

GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59

1 Answers1

3

Instead of a global function use an anonymous function.

$this->Tree->generate($pages, [
    'alias' => 'title',
    'callback' => function ($obj) {
        $id = $obj['data']['id'];

        $return = $this->Html->link('Edit',['action' => 'edit', $id]);
        $return .= $obj['data']['title'];

        return $return;
    }
]);
ADmad
  • 8,102
  • 16
  • 18