Posts

Showing posts from March 19, 2013

create filter in controller symfony2

Sometimes you need to make changes to the Response object, after it is returned by your controller, but before it is rendered as output to the client (e.g. the browser). You may want to set some extra response headers, or " completely mess up the content " of the response. You can accomplish this by creating an event listener that listens to the kernel.response event. I give you a sample event listener which changes the Content-Type header in case the requested format is json and the browser’s accepted response format contains "text/html" in that case, at least in my experience, the browser doesn’t render the JSON string as plain text when the status code is 4xx or 5xx. So in these situations, the event listener changes the “ Content-Type ” to “ text/plain ”, to be sure you always get decent output in the browser. Put the event listener in, for example /src/Acme/DemoBundle/EventListener/ResponseListener.php : namespace Acme\DemoBundle\EventListener;