Content length: 0 in a json response Symfony2 - symfony

Always i get a blank, i have a action in my controller like this
/**
* #Route("/check/{key}.json", defaults={"_format"="json"})
* #Template()
*/
public function processAction($upload_key)
{
/* make thing */
return array('data' => $process_data);
}
in my process.json.twig file i have
{% set res = { 'data': data } %}
{{ res | json_enconde | raw }}
other form
{{ { 'data': data } | json_enconde | raw }}
i've try this too:
{{ 'hello' | json_encode | raw }}
in chrome i get this response:
Connection:close
Content-Length:0
Content-Type:application/json
Date:Mon, 19 Dec 2011 05:13:17 GMT
Server:Apache/2.2.20 (Ubuntu)
X-Powered-By:PHP/5.3.6-13ubuntu3.3
and get nothing from the server, i cant solve this

There are two ways to achieve this, it depends on which you prefer and whether or not your action is supposed to support multiple _format types.
Option A - An action that only returns JSON
You can bypass the template completely.
In your controller remove the #Template annotation and instead return new Response(json_encode($process_data));
Option B - An action that supports different formats OR you just wish to render the JSON in a template
By an action that renders different formats I refer to an action with a route as so:
#Route("/check/{key}.{_format}", defaults={"_format"="json"}
#Template
Although a controller in this question goes down the route of "an action that only supports JSON but you want to render it in a template".
Assuming the controller's processAction returns return array('data' => $process_data); as the question asks then rendering this as JSON inside a template called process.json.twig should be done as follows {{ data|json_encode }}, there is no need to pre-process data or turn it into another array or anything like that inside the template.

Related

How to accept a single, default field in a Symfony form?

I have a REST API written in Symfony3, with help from the FOSRestBundle.
It makes use of Symfony form classes for data input (POST, PATCH, PUT actions), which works great for almost all endpoints.
However I have a child endpoint that sets up relations using a form with a single collectionType. A POST request body looks like this:
curl http://localhost/documents/100/related -d #- <<REQUEST_BODY
{
"related": [
{"id": 14},
{"id": 23}
]
}
REQUEST_BODY
However I would like to ommit the "related" field name as this information is already in the URI and seems redundant here. I would like to adjust the form to accept data like this:
curl http://localhost/documents/100/related -d #- <<REQUEST_BODY
[
{"id": 14},
{"id": 23}
]
REQUEST_BODY
But cannot see how to make a Symfony form behave in this way?
To clarify, I want to accept a single form field without having to specify the name of that field in a JSON request.
I had a similar problem a while back. What worked for me, was to use the form factory to create a named form with an empty name, like so (example when inside a typical controller):
/** #var $formFactory FormFactory */
$formFactory = $this->get('form.factory');
$form = $formFactory->createNamed('', $type, $data, $options);
Be aware that a form configured like this will consume all POST (or GET) data. So, if you can't ensure that only the required data will be present, you might need to use allow_extra_fields

Symfony Routing "_locale" parameter not accepted

I have a problem with the symfony routing.
For an multilanguage projekt I render a Twig template via a job queue for mailing. In this template is a link to a route that requires the "_locale" parameter with "de" or "en" for example. I use the function "{{ url('route', {'_locale': 'de'}) }}" to generate the url.
By rendering the template, I got the following error message:
[Twig_Error_Runtime]
An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("_locale") to generate a URL for route "Route".") in "TemplatePath" at line 5.
Whats my mistake?
Thanks for help
When you are generating URL route, via CLI, the Symfony kernel is missing a HTTP Request, and a Routing->RequestContext.
Thats why, the URL generator cannot find _locale parameter.
To fix it, you must manually create a RequestContext, so, in your command:
$this->getContainer()->get('router')
->setContext(
(new RequestContext())
->setParameter('_locale', 'fr')
);
class BaseCommand extends ContainerAwareCommand
{
protected function getLocale()
{
return $this->getContainer()->get('translator')->getLocale();
}
protected function render($view, $data)
{
return $this->getContainer()->get('templating')->render($view, $data);
}
}
in command
class SomeCommand extends BaseCommand
{
...
$this->render($view, array_merge($data, ['_locale' => $this->getLocale()])
}
in view
{{url('any', {param: 'foo'}|merge(_locale is defined ? {'_locale': _locale } : {}))}}
It's necro time :)
I'm just guessing here, but there's a couple things you can try.
Can you set the locale in your command?
Set the locale for the translator bundle:
$this->getContainer()->get('translator')->setLocale('de');
Set the locale for this session:
$this->getContainer()->get('session')->setLocale('de);
Internationalized routing for Symfony 4.1 and higher
If this applies to you, try this:
url('route.de', {'_locale': 'de'}) }}"
Does your route have 'de' and 'en' set as a requirement?
/**
* Matches /route
* #Route(
* "/route/{_locale}",
* requirements={
* '_locale': 'en|de'
* },
* name="route"
* )
*/
It's an old question but this might help someone out.

Symfony - using twig trans filter on 404 page

I have a 404 error page set up through an event listener triggered by Kernel exceptions:
public function onKernelException(GetResponseForExceptionEvent $event)
{
if ($event->isMasterRequest()) {
$exception = $event->getException();
if ($exception instanceof NotFoundHttpException) {
$response = new Response();
$event->setResponse(
$response->setContent($this->templating->render(
'LandingPageBundle:Error:error404.html.twig',
['welcome_url' => $this->router->generate("welcome")]
))
);
}
}
}
kernel.kernel_exception_listener:
class: S\Project\LandingPageBundle\EventListener\KernelExceptionListener
arguments: [ "#router", "#logger", "#translator", #templating ]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
This works, but when I try to use the trans filter on the twig error404.html.twig template, it does nothing. My locale is being set in a cookie and read by an event listener to Kernel Requests, so I tried adding the following to onKernelException:
$request = $event->getRequest();
$locale = $request->cookies->get('_locale');
$request->setLocale($locale);
After that, including {{ app.request.locale }} in the template displayed the correct locale, however, the trans filter does not seem to be picking this up.
It seems like my problem may be related to Symfony 2.1 set locale and yet that question does not quite fit my exact problem, and I'm not sure what can be done to fix the problem. Ideally my kernel request listener could trigger before the onKernelException, so that it would properly set the locale beforehand, but currently it seems that the kernel request event is not triggered during a 404. I took a look at http://symfony.com/doc/current/components/http_kernel/introduction.html to better understand Symfony's request sequence, but I'm not really clear on the sequence that happens in a bad request, but it looks like in the case of an exception, it skips most of the request flow and goes straight to the response, and as I recall from http://symfony.com/doc/current/book/translation.html#handling-the-user-s-locale
"Setting the locale using $request->setLocale() in the controller is too late to affect the translator. Either set the locale via a listener (like above), the URL (see next) or call setLocale() directly on the translator service."
Is there a way to use the trans filter on a twig templated 404 page?
Try to inject the #translator and use its method setLocale.
['welcome_url' => $this->router->generate("welcome")]
And why did you create link in the listener? You should do it in the template using twig function called path.

http verb for route helper function

I have a restful controller and I want to use the destroy function
this is my route :
+-------------------------------+-----------------------+----------------------+
|URI |Name |Action |
+-------------------------------+-----------------------+----------------------+
|GET|HEAD playwright/play/{play}|playwright.play.show |PlayController#show |
+-------------------------------+-----------------------+----------------------+
|DELETE playwright/play/{play} |playwright.play.destroy|PlayController#destroy|
+-------------------------------+-----------------------+----------------------+
I'm using this link
Delete
And it is always calling the show($id) function. So the it is using the GET verb instead of DELETE.
Is there a way to specify the http verb in the route()helper function?
You need to create a form to do that.
The form needs to POST to the right URI:
{{ Form::open(array('url' => URL::route('playwright.play.destroy'), 'method' => 'DELETE')) }}
{{ Form::submit('Delete me!')}}
{{ Form::close() }}
Information on Laravel forms can be found here

Get original request info after a forward in Symfony 2

I have created a custom Error 403 page using the access_denied_url parameter in security.yml: when showing the new page I want to tell people that the problem happened when trying to access page xxxxx.
$request->headers->get('referer') is empty.
/**
* #Route("/forbidden", name="error_403")
* #Template()
*/
public function error403Action(Request $request)
{
return array('referer' => $request->headers->get('referer'));
}
How can I get information about the original Request (the one that resulted in this forward)?
It got solved calling {{ app.request.server.get('PHP_SELF') }} directly in the Twig template.

Resources