简体   繁体   中英

How to get a segment URL cakephp 3

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM