【问题标题】:my view action not showing any data. CakePHP我的视图操作没有显示任何数据。 CakePHP
【发布时间】:2011-08-17 11:55:55
【问题描述】:

这是我在 newsses/index.ctp 中的链接

$this->Html->link(__("Read more >>", TRUE), array('action'=>'view', $newss['Newsse']['title']));

这是我在 newsses_controller.php 中的视图代码:

function view($title = NULL){
    $this->set('title_for_layout', __('News & Event', true));

    if (!$id) {
        $this->Session->setFlash(__('Invalid News.', true), 'default', array('class' => 'error')); 
        $this->redirect(array('action'=>'index'));
    }
    $this->set('newsse', $this->Newsse->read(NULL,$title));
    $this->set('newsses', $this->Newsse->find('all'));
}

但它没有显示任何内容, 我想做这样的路线: “newsses/view/2”到“newsses/view/title_of_news”

请帮帮我....

【问题讨论】:

  • 只是一个注释,你可以给你的模型命名为 News 和 cake 就会明白控制器也会是 News

标签: cakephp view routes param


【解决方案1】:

您正在使用Model::read() 方法方法,该方法将您要访问的模型表中的行的id 作为第二个参数。在这种情况下最好使用 find 。您无需在模型或控制器中构建新方法,只需编辑当前的 view 方法即可。

# in newsses_controller.php:
 function view($title = null) {
     $this->set('title_for_layout', __('News & Event', true));

     if (!$id) {
        $this->Session->setFlash(__('Invalid News.', true), 'default', array('class' => 'error')); 
        $this->redirect(array('action'=>'index'));
    }

    $this->set('newsse', $this->Newsse->find('first', array(
        'conditions' => array('Newsse.title' => $title)
    ));
    $this->set('newsses', $this->Newsse->find('all'));
}

或者,您可以制作一种更加混合的形式,当给出数字标题时,仍然可以通过 id 查看(假设您从来没有标题仅由数字字符组成的新闻项目,例如“12345”)。

# in newsses_controller.php:
 function view($title = null) {
     $this->set('title_for_layout', __('News & Event', true));

     if (!$id) {
        $this->Session->setFlash(__('Invalid News.', true), 'default', array('class' => 'error')); 
        $this->redirect(array('action'=>'index'));
    } else if (is_numeric($title)) {
        $this->set('newsse', $this->Newsse->read(NULL, $title));
    } else {
        $this->set('newsse', $this->Newsse->find('first', array(
            'conditions' => array('Newsse.title' => $title)
        ));
    }

    $this->set('newsses', $this->Newsse->find('all'));
}

最后,您还可以用(更短的)自定义 findBy 方法替换我示例中的 find 方法(有关此内容的更多信息,请参阅 documentation)。

$this->Newsse->findByTitle($title);

【讨论】:

  • 还有路由、url 参数怎么样,我想将标题设为参数,并且我希望标题小写并带有下划线,以及控制器中的视图函数如何读取该参数...?。跨度>
  • 设置默认路由后,/newsses/view/this_is_a_title 将自动按照您想要的方式工作。
  • 并且在创建项目标题时应使用您对标题的要求(例如在add() 方法中)。您可以使用Inflector::slug() 轻松创建一个漂亮的标题。
【解决方案2】:

为此,您需要在模型中创建一个新方法,该方法将按新闻标题显示结果。这时候你使用 $this->Newsse->read(NULL,$title))。您在读取方法中使用 $title,而此读取方法在模型中搜索新闻 id。因此,您只需要在模型类中创建一个新方法,例如 readByTitle($title){ 在此处编写查询以按标题获取新闻}。并在您的控制器中使用此方法。 $this->Newsse->readByTitle(NULL,$title))

【讨论】:

    猜你喜欢
    • 2016-07-23
    • 2018-08-07
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2017-02-06
    • 1970-01-01
    相关资源
    最近更新 更多