1

I'm trying to set 404 HTTP response status from a block's function.

With this code works

http_response_code(404);
exit;

but no way to to set the 404 status without exiting, i've found only solutions for controllers.

2

You shouldn't be modifying the response code with in a block, it should be in the controller. Your block should only contain logic that is used within template files to format data etc.

But in your controller to return a 404 you can use the following after injecting the resultForwardFactory \Magento\Framework\Controller\Result\ForwardFactory

return $this->resultForwardFactory->create()->forward('noroute');

I've attached a few core Magento examples of it.

https://github.com/magento/magento2/blob/2.4-develop/app/code/Magento/Catalog/Controller/Category/View.php

https://github.com/magento/magento2/blob/2.4-develop/app/code/Magento/Catalog/Controller/Product/View.php

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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