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?

1 Answer 1

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;
    }
]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.