2011-06-07 51 views
1

我與CakePHP的發展,這是我的頁面控制器:

<?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` DESC LIMIT 2;"); 
     $this->set('cursos', $select); 
     //$this->set($select); 

    } 
} 

$this->set('cursos', $select);不工作,這是錯誤:

Notice (8): Undefined variable: cursos[APP/views/pages/home.ctp, line 36]. 

任何人都可以幫到我嗎?

+0

被警告PagesController是靜態頁面,即不網頁:

第一種方法解決方案需要數據。考慮一下,您將針對您網站中的每個靜態頁面運行此查詢。如果您需要執行數據庫提取,最好創建一個'CursosController'。 – Eagle 2014-02-12 11:42:30

回答

7

這是因爲您在$this->render()調用後設置它。渲染調用是在視圖被加載並執行時。

+0

移動loadModel並將('cursos',..)調用設置爲$ this-> render()調用之前,它將起作用。 – 2011-06-07 21:04:47

0

這兩種方法都適用於我,我已經使用過。 (由於渲染調用您的設置語句之前)

<?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 

    } 
} 
?> 

第二種方法

<?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(); 
     } 


    } 
} 
?> 
相關問題