Magento2 how to getRequest
If you are trying this from a controller that extends Magento\Framework\App\Action\Action
you can get the request with $this->getRequest()->getPost()
.
If you are in a custom class, you need to inject the request in the constructor.
<?php
namespace Namespace\Module\Something;
class ClassName
{
protected $request;
public function __construct(
\Magento\Framework\App\RequestInterface $request
....//rest of parameters here
) {
$this->request = $request;
...//rest of constructor here
}
public function getPost()
{
return $this->request->getPostValue();//in Magento 2.*
}
}
Hi you can get it easily in models, blocks and controllers by using:
$this->getRequest()->getPost()
Or add Magento\Framework\App\RequestInterface
to the constructor parameters in your own classes:
<?php
namespace MyModuleNameSpace\MyModule\Block
use Magento\Framework\App\RequestInterface;
class MyClass
{
/**
* Request instance
*
* @var \Magento\Framework\App\RequestInterface
*/
protected $request;
/**
* @param RequestInterface $request
*/
public function __construct(RequestInterface $request)
{
$this->request = $request;
}
public function getMyPostParams()
{
$postData = $this->request->getPost();
}
}
This should work, just test it. Compare and see what is missing.
<?php
namespace MyModuleNameSpace\MyModule\Block
use Magento\Framework\App\RequestInterface;
class MyClass extends \Magento\Framework\View\Element\Template
{
/**
* Request instance
*
* @var \Magento\Framework\App\RequestInterface
*/
protected $request;
/**
* @param RequestInterface $request
*/
public function __construct(
RequestInterface $request,
\Magento\Framework\View\Element\Template\Context $context,
array $data = [])
{
$this->request = $request;
parent::__construct($context, $data);
}
public function getMyPostParams()
{
$postData = $this->request->getPost();
}
}