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.
4 Answers 4
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– nuwaus2017年10月03日 11:47:55 +00:00Commented Oct 3, 2017 at 11:47
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');
}
At BLock class, you don't need to inject this class. Use
$this->getRequest() instead of $this->request.
-
can we use same code in block files?Jafar Pinjar– Jafar Pinjar2019年08月22日 11:15:26 +00:00Commented Aug 22, 2019 at 11:15
=> 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
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->getParam("order_id");
}