2012-10-08 44 views
1

在我的CakePHP應用程序連接了以下路線:CakePHP的2.x的反向路由鏈路助手

Router::connect('/:city/dealer/:id', 
    array('controller' => 'dealers', 'action' => 'view'), 
    array(
     'pass' => array('city', 'id'), 
     'city' => '[a-z]+', 
     'id' => '[0-9]+' 
     ) 
    ); 

這個偉大的工程,使:domain.com/washington/dealer/1

但如何在視圖中爲此URL生成適當的HTML鏈接?如果我只是這樣做:

echo $this->Html->link(
    'Testlink', 
    array('washington', 'controller' => 'dealers', 'action' => 'view', 1) 
); 

它增加了所有PARAMS到生成的鏈接的結尾:

http://domain.com/dealers/view/washington/1

我該如何正確做到這一點?

+0

如果你使用會發生什麼「/:城市/:控制器/:id'你的路線?你想讓其他控制器使用相同的模式嗎? –

+0

當我使用'/:city /:controller /:id'時,Cake抱怨domain.com/washington/dealer/1丟失的DealerController ... 基本上只有這個控制器在應用程序中... – Sebastian

+0

嘗試domain.com/華盛頓/經銷商/ 1(注意經銷商) –

回答

2

我相信你仍然需要指定參數,可以像這樣:

echo $this->Html->link('Testlink', 
    array('controller' => 'dealers', 'action' => 'view', 'city' => 'washington', 
                 'id'=> 1)); 

蛋糕已經在食譜一個類似的例子:

<?php 
// SomeController.php 
public function view($articleId = null, $slug = null) { 
    // some code here... 
} 

// routes.php 
Router::connect(
    '/blog/:id-:slug', // E.g. /blog/3-CakePHP_Rocks 
    array('controller' => 'blog', 'action' => 'view'), 
    array(
     // order matters since this will simply map ":id" to $articleId in your action 
     'pass' => array('id', 'slug'), 
     'id' => '[0-9]+' 
    ) 
); 

// view.ctp 
// this will return a link to /blog/3-CakePHP_Rocks 
<?php 
echo $this->Html->link('CakePHP Rocks', array(
    'controller' => 'blog', 
    'action' => 'view', 
    'id' => 3, 
    'slug' => 'CakePHP_Rocks' 
)); 
+0

對不起,我應該提到這個例子。問題在於,LinkHelper仍然將參數放在最後。這是從您的/蛋糕示例生成的鏈接: http://domain.com/dealers/view/city:washington/id:1 – Sebastian

0

塞巴斯蒂安嗨它可能爲時已晚,以幫助你,但我可以幫助其他人解決這個問題。解決問題的關鍵是添加到Helper類中的url方法。我在View/Helper中創建了一個AppHelper.php。它看起來像這樣。我改變了我的參數爲你的城市。

查看/助手/ AppHelper.php

<?php 
App::uses('Helper', 'View'); 
class AppHelper extends Helper { 

    function url($url = null, $full = false) { 
      if (is_array($url)) { 
        if (empty($url['city']) && isset($this->params['city'])) { 
          $url['city'] = $this->params['city']; 
        } 

        if (empty($url['controller']) && isset($this->params['controller'])) { 
          $url['controller'] = $this->params['controller']; 
        } 

        if (empty($url['action']) && isset($this->params['action'])) { 
          $url['action'] = $this->params['action']; 
        } 
      } 

      return parent::url($url, $full); 
    } 

} 
?> 

然後,我創建像

Router::connect('/:city/dealer/:id', 
array('controller' => 'dealers', 'action' => 'view', 'id'=>':id'), 
array('pass' => array('city', 'id'), 
     'city' => '[a-z]+', 
     'id' => '[0-9]+' 
)); 

希望路線這有助於:)