PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] How to alter view blocks content from controller in CakePHP 3?

 February 21, 2022     cakephp, cakephp-3.0     No comments   

Issue

Inside Layouts/default.ctp you will see something like this at line 39:

        <div class="header-title">
            <span><?= $this->fetch('title') ?></span>
        </div>

fetch suggests that it is a view block. I couldn't find this view block anywhere.

Currently it just displays the capitalized plural form of controller. Meaning to say if you are at /users/add , the fetch('title'); gives you 'Users'

I want to change it. So I tried the following:

$this->set('title', 'Login');

in the /users/login controller action.

Did not work.

I also tried

$this->assign('title', 'Login');

in the /users/login controller action.

I get this error message:

Call to undefined method App\Controller\UsersController::assign()

I read the docs and from here

I get

Assigning a block’s content is often useful when you want to convert a view variable into a block. For example, you may want to use a block for the page title, and sometimes assign the title as a view variable in the controller:

Emphasis mine.

This suggests that you can use assign inside controller. I think I have proven that this is false.

Perhaps there is a typo in the documents. Please advise how I can set the title


Solution

This is how to do it thanks to dakota of the irc channel #cakephp.

Inside UsersController.php:

$this->set('title', 'Login');

Inside src/Template/Layouts/default.ctp

above the $this->fetch('title');

write:

if (isset($title)) {
    $this->assign('title', $title); 
}

The question would be how does cakephp 3 set the default value?

Answer is found in https://github.com/cakephp/cakephp/blob/3.0/src/View/View.php#L468

Append image just in case link rot

enter image description here

Where you can see that it will be defaulted to the view path



Answered By - Kim Stacks
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing