Tuesday, December 28, 2021

[FIXED] Connecting `new \Cake\View\ViewBuilder()` to the main `\Cake\Http\ServerRequest`

Issue

I'm rendering a view template into a variable via a new, standalone ViewBuilder.

$builder = new \Cake\View\ViewBuilder();
$builder->setLayout('my_layout');
$builder->setTemplate('my_template');

The above template contains a form.

echo $this->Form->create(null, array(
    'type' => 'POST',
    'url' => '/',
)).PHP_EOL;
$this->Form->unlockField('my_input');
echo $this->Form->end();

When submitted, it results in the below error.

'_Token' was not found in request data.

As far as I understand, the tokens aren't being added because the FormHelper receives false when it checks for $this->_View->getRequest()->getParam('_Token'), and that is because this new ViewBuilder isn't connected to the actual request the application operates on.

Is there a way to connect my new ViewBuilder to the main Cake\Http\ServerRequest of the application?


Solution

You can pass it to $builder->build, it's the the 2nd argument, you can normally get it from $this->getRequest().



Answered By - ahoffner

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.