6

Assume I have a URL like this,

http://mystore.com/cms/sales/order/view/order_id/286/

I want to get values of the order_id which is 286,

Please help with some example or snippet in Magento 2.

5

By ObjectManager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();  
$request = $objectManager->get('Magento\Framework\App\Request\Http');  
echo $param = $request->getParam('order_id');

By Factory Method

protected $request;

public function __construct(
    ...
    \Magento\Framework\App\Request\Http $request,
    ...
) {
   $this->request = $request;
}

$this->request->getParam('order_id');

Note: Do not use objectManager directly in files as Magento 2 coding standards.

  • The ObjectManager way worked for me, I was trying to inject from Magento\Backend\App\Action, but injection didn't work so I tried the ObjectManager method, it works, thanks. – nuwaus Oct 3 '17 at 11:47
3

First, you need to inject \Magento\Framework\App\Request\Http at _constructfunction then using

protected $request;
    public function __construct(
        \Magento\Framework\App\Request\Http $request,
        ....//rest of parameters here
    ) {
       $this->request = $request;
       ...//rest of constructor here
    }
    public function getIddata()
    {
    // use 
    $this->request->getParams(); // all params
        return $this->request->getParam('order_id');
    }
2

In a controller which extends Magento\Framework\App\Action\Action you can get the request with $this->getRequest()->getPost().

In a custom class, you need to inject the request in the constructor in below way:

public function __construct(
        \Magento\Framework\App\Request\Http $request,
        ....//rest of parameters here
    ) {
       $this->request = $request;
       ...//rest of constructor here
    }

Then you can get the values like below:

public function getPost()
{
    return $this->request->getParams();
}
2

=> Factory Method :

<?php
namespace Namespace\Module\Something;
class ClassName 
{
    protected $request;
    public function __construct(
        \Magento\Framework\App\Request\Http $request,
        ....//rest of parameters here
    ) {
       $this->request = $request;
       ...//rest of constructor here
    }
    public function getPost()
    {
        return $this->request->getParam("order_id");
    }
}

=> Object Manager :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();  
$request = $objectManager->get('Magento\Framework\App\Request\Http');  
echo $request->getParam('order_id');

=> Note : Do not use direct object manager as magento coding format

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.