Pregunta

I want to get POST data in Model file, Which is my custom file of AccountManagement

/app/code/[Vendor]/[Module]/Model/AccountManagement.php

Note:

I can access it through $_POST, 'superglobal' variable but i don't wanna use it that way, Because it's not valid for Magento standard.

Because Magento use to featch POST and REQUEST data using this method in Controller.

$this->postData = $this->getRequest()->getPostValue();

But i am not able to use same method in Model file.

So anyone have any idea to fetch POST data in Model file IN Magento 2x, As per Magento Standard

¿Fue útil?

Solución

Please try below code. We will inject Http class in the constructor and use that to get post data. This is a standard way of Magento 2

<?php
namespace Namespace\Module\Model;
class ModelClassName 
{
    protected $request;
    public function __construct(
        \Magento\Framework\App\Request\Http $request,
    ) {
       $this->request = $request;
    }
    public function getPost()
    {
        return $this->request->getPost();
    }
}

Otros consejos

Just for reference, it worked for me.

$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();
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top