Magento 2 Controller Output Types

Magento 2 now introduces the Framework result object for handing requests that will handling non page results such as JSON, redirects and other non html returns.

So to use the result factory in your controller in your controller construct simply have the following code:

$this->resultFactory = $context->getResultFactory();

Then in the run method simply write the following:

$result = $resultRedirect = $this->resultFactory->create($type);

So the type value has to be one of the following constants:

JSON

This is for returning a JSON object from a controller with the correct mime type in the response. For returning json there are to methods:

return $result->setData(['variable'=>'value']);

The first method allows you to pass a php associative array which Magento 2 framework will run the serialization for you.

return $result->setJsonData('{"variable": "value"}');

The second method allows for you to set a raw json string to respond with instead of letting Magento 2 handle serialization of the reponse.

Raw

This is for setting raw string and binary contents. To use this simply run the following.

return $result->setHeader('Content-Type','text/plain')->setContents('string');

Redirect

This is for redirecting a user to another page via a 301, 302 and 307 based redirects. To use this simply use the following:

return $result->setUrl('https://www.google.co.uk');
return $result->setPath('checkout', ['_secure' => true]);

Forward

Occasionaly you will want to do a internal redirect to a another controller without having the client to do a second request for this we have the forward type. To use this simply do the following.

return $result->setModule('moduleName')->setController('controller')->setParam(['id'=>1])->view('action');

return $result->setController('controller')->view('action');

The convention is controller should be folder name inside your modules ‘Controller’ folder and action should be the name of your action php file with out the php extension. As for moduleName you can normally find out what this should be in you routes.xml file and it should be the value set in frontName attribute set in your route declaration xml.

Please note if moduleName is not given then Magento 2 will assume that the module is the current one.

Layout and Page

The last two is to simply use xml layout handling to render the contents. The only difference is that layout will not have a default layout handle so you will need to assign layout handles and Page will assign the default and controler specific handles. As expected Page extends the Layout object since there only difference is the fact that layout assumes no layout handlers to begin with.


Tags: magento2mvcmvvmjsonredirect