2016-11-11 25 views
0

大家好我是Zendframework2的新手。控制器中paginator的訪問標識

我在view\partial\paginator.phtml

<a href="<?php echo $this->url($this->route);?>?page=<?php echo $page; ?>?id=<?php echo $this->id?>"> 

下面一行在瀏覽器中,它看起來像http://new_project.localhost/districts?page=2?id=4

new_project是我的項目的名稱,區是控制器的途徑和id=4 ,4號這我想訪問控制器。

我想:

$_GET['id'];        

$this->params()->fromRoute('id'); //also 

$this->params()->fromQuery('id'); //also 

但是這些作品的非。

如何在控制器中訪問此id

+0

玉傢伙我解決了它:我變了樣paginator.php線: Skylink

+0

?更改爲&。 – Skylink

回答

0

我解決它,只是把情況如下圖所示:

if (isset($_GET['id'])) 
{ 
    // perform operation here.  
} 
0

不要建立自己的一個元素標籤HREF自己,但使用框架應該像你。

網址視圖助手:

// $this->url($routeName, $routeParams, $options, $reuseMatchedParams = false) 
$this->url('my/route', ['id' => $object->getId()], ['query' => ['page' => $page]]) 

控制器插件:

$this->params('id') // will take ID either from routeParameters or queryParameters. 
$this->params()->fromRoute('id') // will take the id from the routeParameters 
$this->params()->fromQuery('page') // will take the page from the route query 

所以,當你有一個路線與routeParameter ID,但您的查詢也有ID內它查詢它的最佳實踐繼續使用$this->params()->fromRoute('id')$this->params()->fromQuery('id'),以便始終知道價值來自哪裏,而不是使用$this->params('id')

params插件一樣,您還可以在第二個參數中定義默認值,如:$this->params()->fromQuery('page', 1)。所以如果用戶沒有提供,頁面將始終爲1。第二個參數的缺省值是null。希望這可以幫助,讓你停止使用$_GET['bla']

0

我覺得您的網址應該是這樣的:

http://new_project.localhost/districts?page=2&id=4 
              ^
             not ? 

由於錯誤的,你所做的解析器可能不會在您的網址正確解析ID意味着你不能像你試過的那樣訪問它。

如果在url中使用the url view helper來渲染查詢參數會更好,那麼你就不會犯這樣的錯誤。您可以在StackOverflow上檢查this post,以瞭解如何使用url視圖助手將查詢參數添加到url。在你的情況下,它會是這個樣子:

<?php 
    $href = $this->url($this->route, [], ['query' => [ 
     'page' => $page, 
     'id' => $id, 
    ]]); 
?> 
<a href="<?php echo $href ?>"> 

現在你得到正確的網址:

http://new_project.localhost/districts?page=2&id=4 

含義解析器還管理正確解析的ID。 您應該能夠訪問它現在像你這樣嘗試:

$this->params()->fromQuery('id'); //returns your id from the url