2

Hi I got trouble in retrieve URL segment CAkephp3 in view. I want to get the ID from current URL.

Lets say my URL is http://localhost/admin/financial_agreements/edit/50 and I want redirect to http://localhost/admin/financial_agreements/do_print/50 simply :

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

I try debug

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

But its produce : admin/financial_agreements/edit/50

whats called in 50 ? I need that 50 inside my "url->build" urlPrint

sorry for bad english.

Anyhelp will appreciate. thanks.

2 Answers2

3

You can use the Request object to get request data (including url parameters) within views.

Try this in your view:

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

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

That will return an array of all non-named parameters that were passed after the action's name in the URL. Example: /mycontroller/myaction/param1/param2. So in this example, $this->request->getParam('pass') will produce an array like: [0 => 'param1', 1 => 'param2'].

Bonus answer: you can also 'name' parameters in the URL, like: /mycontroller/myaction/some_name:some_value. To retrieve this kind of named parameters, you would do the same trick but using: $this->request->getParam('named') (Use the argument 'named' instead of 'pass').

More info: https://book.cakephp.org/3.0/en/controllers/request-response.html https://book.cakephp.org/3.0/en/development/routing.html#passed-arguments

Pang
  • 9,564
  • 146
  • 81
  • 122
YOMorales
  • 1,926
  • 1
  • 15
  • 25
  • 1
    Note that named parameters are deprecated as of Cake 3. You can instead use more standard URL query strings like `?some_name=some_value`, and access them with `$this->request->getQuery('some_name')`. This is discussed on the same links @YOMorales provided. – Greg Schmidt Dec 10 '17 at 15:44
  • Thanks, yeah, I forgot about the deprecation. I still do like named params. :P – YOMorales Dec 10 '17 at 17:36
2

Assuming that your edit function follows standard practices, you'll have something like this:

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

Then in edit.ctp, you can get the id of the current record very simply as $financialAgreement->id, so your URL will be generated with

$this->Url->build(['controller' => 'financial_agreements', 'action' => 'do_print', $financialAgreement->id], true)
Greg Schmidt
  • 5,010
  • 2
  • 14
  • 35