Problem:
You can get the error message Notice (8): Undefined variable in CakePHP while passing variable value from Controller to View. How to overcome this error?Solution:
If you mistakenly create a method in predefined Controller "PagesController.php" which is automatically created by default. So don't touch or use "PagesController.php". you need to create own Controller ans create method and pass variable.In other clear wording "do not use PagesController.php file, create own controller class"
Example:
See below incorrect code:File: src\Controller\PagesController.php
<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
class PagesController extends AppController
{
public function display()
{
$path = func_get_args();
$count = count($path);
if (!$count) {
return $this->redirect('/');
}
$page = $subpage = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
$this->set(compact('page', 'subpage'));
try {
$this->render(implode('/', $path));
} catch (MissingTemplateException $e) {
if (Configure::read('debug')) {
throw $e;
}
throw new NotFoundException();
}
}
public function myshow() {
$this->set('color', 'pink');
}
}
File: \src\Template\Pages\myshow.ctp
<?php
echo $color;
?>
See below Correct code:
Create a new File BooksController
File: src\Controller\BooksController.php
<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
class BooksController extends AppController
{
public function index()
{
}
public function myshow() {
$this->set('color','pink');
}
}
Create a new file myshow.ctp
File: \src\Template\Books\myshow.ctp
<?php
echo $color;
?>
So do not use PagesController.php file, create own controller class
0 comments:
Post a Comment