Search code examples
phpsymfonysymfony-formsesi

Symfony ESI get POST Parameter for FORM submit or call ESI as POST


I have a cached site which have a form in it which should not be cached. I use ESI for it. When the form is submit I need to get the POST Parameter in my controller. Symfony let me get the Request Parameter 'form' not the real POST Data or is there a good way to get them.

{{ render_esi(controller('MyBundle:Form:staticForm', {'form': 'sidebar'}))}}

Setting them in twig will not work because of Parent Page Cache.

{{ render_esi(controller('MyBundle:Form:staticForm', {'form': 'sidebar', 'request': }))}}

So how to get the post parameter in my controller currently the code shown here only gets me the ESI data:

public function staticFormAction(Request $request) {
    // ..
    $form->handleRequest($request);// will not work because:
    $request->get('firstName'); // is empty when called by ESI

How I can get the Parameters from the Parent Request?

Hacky solution

Currently the only solution I found is for me too hacky
TWIG:

{{ render_esi(controller('ClientWebsiteBundle:Form:staticForm', app.request.request.all|merge({'form': 'sidebar'}), app.request.query.all)) }}

PHP:

$data = ($request->get('myFormName'));
if (count($data)) {
    // Forms uses $request->request
    $request->request->set('myFormName', $data);
    $request->setMethod('POST');
}

Additional

After a little research and look into symfony core code I need to change the ESI to Post so my question is know "How to call ESI as POST method not GET?"

Solution

Using requestStack like Chris Tickner posted seems the post solution.


Solution

  • ESI is an edge-side include, which means it is not designed to handle POST data. By default, reverse proxies like Varnish or Symfony's HttpCache kernel, see the ESI as a URL ("/_proxy?_controller=x&params=etc") which they include by GET-ing it from your app. This is why you are finding this difficult.

    However, no proxy is going to cache a POST request, so you could, during a POST request, access the master request using the request_stack service.

    // if POST
    $master_request = $this->get('request_stack')->getMasterRequest();
    $form->handleRequest($master_request);
    

    This should do the trick if you are using the Symfony HttpCache.

    http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/RequestStack.html