CakePHP $this->set() don't works in Pages Controller
I am developing with CakePHP and this is my Page Controller:
<?php
class PagesController extends AppController
{
var $name = 'Pages';
var $helpers = array('Html', 'Session');
var $uses = array();
function display()
{
$path = func_get_args();
$count = count($path);
if (!$count) {
$this->redirect('/');
}
$page = $subpage = $title_for_layout = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
if (!empty($path[$count - 1])) {
$title_for_layout = Inflector::humanize($path[$count - 1]);
}
$this->set(compact('page', 'subpage', 'title_for_layout'));
$this->render(implode('/', $path));
$this->loadModel('Curso', 2);
$select = $this->Curso->query("SELECT * FROM cursos ORDER BY `cursos`.`created` D开发者_StackOverflow中文版ESC LIMIT 2;");
$this->set('cursos', $select);
//$this->set($select);
}
}
But $this->set('cursos', $select);
don't works, this is the error:
Notice (8): Undefined variable: cursos[APP/views/pages/home.ctp, line 36].
Anyone can help me?
That's because you're setting it after the $this->render()
call. The render call is when the view gets loaded and executed.
Both method worked for me, i have already used.
First Method solution for: (Because the render call is before your set statement)
<?php
class PagesController extends AppController
{
var $name = 'Pages';
var $helpers = array('Html', 'Session');
var $uses = array();
function display()
{
$this->loadModel('Curso', 2);
$select = $this->Curso->query("SELECT * FROM cursos ORDER BY `cursos`.`created` DESC LIMIT 2;");
$this->set('cursos', $select);
//Now put your rest of code
}
}
?>
Second Method
<?php
class PagesController extends AppController
{
var $name = 'Pages';
var $helpers = array('Html', 'Session');
var $uses = array();
function display()
{
//put your code
$this->loadModel('Curso', 2);
$select = $this->Curso->query("SELECT * FROM cursos ORDER BY `cursos`.`created` DESC LIMIT 2;");
$this->set('cursos', $select);
try {
$this->render(implode('/', $path));
}
catch (MissingViewException $e) {
if (Configure::read('debug')) {
throw $e;
}
throw new NotFoundException();
}
}
}
?>
精彩评论