Add data to request data [solved]


I need to add a variable in a controller that does not come from a form.
Before, in 3.x, I could add variables to the request->data array :
$this->request->data[‘new_var’] = $value;

I tried several ways with getData but was unsuccessful :
$this->request->getData()->new_var = $value;
$this->request->getData(‘new_var’) = $value;

It seems that getData is read only;

How can I do this in 4.x ?

As far as I know “this->request->getData()” is immutable

Thank you but that does not help.
How can we add variables in the request data ?
Of course, you can do :
$article->my_var = $value;
and this works fine.

But let’s take an example :
some times, I need to assign a particular name to an article.
So i will write :
$article->name = new_name;
It’s OK.

But then, validation will fail and I need validation for other cases.

Then, as I am writing this post, I wondered if validation could by bypassed.
I’ll check the cookbook and let you know.

Can you do this?

$data = ['name' => 'New Name'] + $this->getRequest()->getData();
$this->Articles->patchEntity($article, $data);

Any ‘name’ key in the request data will be overwritten by the value assigned.

I usually convert it to array and add them in (using it on Cake 4.2)

$receivedData = $this->request->getData();
$receivedData['type'] = 'my custom data';
$this->Articles->patchEntity($article, $receivedData );

You can add data to the request:

$this->request = $this->request->withData('key_name', $new_value);

Here is a useful section of the book: Using immutable Responses


Thank you.
This seems to be the right way.
I’m not at work currently but I will try this tomorrow.

Which solution is best will very much depend on whether you want this particular bit of data to be set all the time, despite what might be posted, or if you want to use it only as a default when something else isn’t given.

Thank you for this solution. It works perfectly.

There are many cases when you have to add data into the request.
Examples :
When you upload a file, the name is not in the request.
If you need an information from another (non related) table or even from another DB.

In any case, this helps a lot.