如何获取段 URL cakephp 3

How to get a segment URL cakephp 3

您好,我在检索视图中的 URL 段 CAkephp3 时遇到了问题。我想从当前 URL.

获取 ID

假设我的 URL 是 http://localhost/admin/financial_agreements/edit/50 我想重定向到 http://localhost/admin/financial_agreements/do_print/50 简单地说:

var urlPrint = "<?=$this->Url->build(['controller' => 'financial_agreements', 'action' => 'do_print', 'I NEED ID FROM CURRENT'], true)?>";

我尝试调试

<?=debug($this->Url->build()); die();?>

但它的产物:admin/financial_agreements/edit/50

50 叫什么?我的 "url->build" urlPrint

中需要 50

抱歉英语不好。

任何帮助将不胜感激。 谢谢。

您可以使用 Request 对象在视图中获取请求数据(包括 url 参数)。

在您的视图中试试这个:

$this->request->getParam('pass') //CakePHP 3.4+

$this->request->params['pass'] // CakePHP 3.3

这将 return 一个数组,其中包含在 URL 中的操作名称之后传递的所有未命名参数。示例:/mycontroller/myaction/param1/param2。所以在这个例子中,$this->request->getParam('pass') 将生成一个数组,如:[0 => 'param1', 1 => 'param2'].

额外答案:您还可以在 URL 中 'name' 参数,例如:/mycontroller/myaction/some_name:some_value。要检索这种命名参数,您可以使用相同的技巧,但使用:$this->request->getParam('named')(使用参数 'named' 而不是 'pass')。

更多信息: https://book.cakephp.org/3.0/en/controllers/request-response.html https://book.cakephp.org/3.0/en/development/routing.html#passed-arguments

假设您的编辑功能遵循标准做法,您将拥有如下内容:

public function edit($id) {
    $financialAgreement = $this->FinancialAgreements->get($id);
    ...
    $this->set(compact('financialAgreement'));
}

然后在edit.ctp中可以很简单的得到当前记录的id如$financialAgreement->id,所以你的URL会生成

$this->Url->build(['controller' => 'financial_agreements', 'action' => 'do_print', $financialAgreement->id], true)