【问题标题】:How to get a segment URL cakephp 3如何获取段 URL cakephp 3
【发布时间】:2017-12-09 04:47:18
【问题描述】:

您好,我在检索视图中的 URL 段 CAkephp3 时遇到了麻烦。我想从当前 URL 获取 ID。

假设我的网址是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 ?我需要 50 在我的“url->build”urlPrint

抱歉英语不好。

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

【问题讨论】:

    标签: php cakephp cakephp-3.x


    【解决方案1】:

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

    在你的视图中试试这个:

    $this-&gt;request-&gt;getParam('pass') //CakePHP 3.4+

    $this-&gt;request-&gt;params['pass'] // CakePHP 3.3

    这将返回在 URL 中的操作名称之后传递的所有未命名参数的数组。示例:/mycontroller/myaction/param1/param2。所以在本例中,$this-&gt;request-&gt;getParam('pass') 将生成一个数组,如:[0 =&gt; 'param1', 1 =&gt; 'param2']

    奖励答案:您还可以在 URL 中“命名”参数,例如:/mycontroller/myaction/some_name:some_value。要检索这种命名参数,您可以使用相同的技巧,但使用:$this-&gt;request-&gt;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

    【讨论】:

    • 请注意,从 Cake 3 起,命名参数已被弃用。您可以改用更标准的 URL 查询字符串,如 ?some_name=some_value,并使用 $this-&gt;request-&gt;getQuery('some_name') 访问它们。这在@YOMorales 提供的相同链接上进行了讨论。
    • 谢谢,是的,我忘记了弃用。我仍然喜欢命名参数。 :P
    【解决方案2】:

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

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

    然后在edit.ctp中,你可以很简单的得到当前记录的id为$financialAgreement-&gt;id,这样你的URL就会生成

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

    【讨论】:

      猜你喜欢
      • 2015-12-05
      • 2016-03-17
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 2011-08-15
      • 1970-01-01
      相关资源
      最近更新 更多