10

I have already know how to get the POST value of Request.

I used to use this code below to get the value:

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

But how can I set the value of POST. Something like:

$this->getRequest()->setPostValue('value',$value);

or

$this->getRequest()->set('value',$value);

Is it possible?

1
  • 1
    $this->getRequest()->setPostValue('value',$value); Jan 5, 2018 at 9:23

3 Answers 3

14

Yes you can set value using setPostValue() check below for set of array,

<?php
namespace Namespace\Modulename\Model;

class Request extends \Magento\Framework\DataObject
{
public function __construct(
    \Magento\Framework\App\RequestInterface $request,
    array $data = []
) {
    $this->request = $request;
    parent::__construct($data);
}

public function setPostCustomValue(){
    /* for single value */
    $this->request->setPostValue('test','store my value');

    /* for multiple array */
    $post = [
            'customer' => [
                'firstname' => 'test firstname',
                'lastname' => 'test lastname',
                'email' => '[email protected]',
                'default_billing' => '_item1',
            ],
            'address' => ['_item1' => []],
        ];
    $this->request->setPostValue('customarray',$post);
}
3
  • If I have already have the customer and address key in my PostValue, It change the value or insert the new key-value?
    – Nero Phung
    Jan 5, 2018 at 9:23
  • It just update the value if aleady exist then update otherwise keep it Jan 5, 2018 at 9:29
  • 1
    You can set single value as well as array value. Jan 5, 2018 at 9:34
4

You can try below code to set param

$this->getRequest()->setParam('value',$value);
2
  • It just change the Param, not the post value.
    – Nero Phung
    Jan 5, 2018 at 9:21
  • 1
    it will work, this param will be set to the post data, if this param is already in post data it will overwrite that value
    – Piyush
    Jan 5, 2018 at 9:25
3

You can write in you controller and it is the way worked for me:

<?php

namespace Vendor\ProductComments\Controller\Post;

use Magento\Framework\App\Action\Action;    

class Index extends Action
{
    public function __construct(
        ....
        ....
    ) {
        ....
        ....
    }
    public function execute()
    {
        $this->getRequest()->setPostValue('timestamp', '24343256534345');
    }
}
3
  • Yes. It is the correct answer!
    – Nero Phung
    Jan 5, 2018 at 9:25
  • 1
    Thank You. It worked for me as well. It will change the posted value for 'timestamp'. In your case change it to 'value'.
    – P S
    Jan 5, 2018 at 9:26
  • Yes. It's easy to understand!
    – Nero Phung
    Jan 5, 2018 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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