简体   繁体   中英

CakePHP use $this in view function

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?

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;
    }
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM