Skip to content

Instantly share code, notes, and snippets.

@hellomedia
Last active August 29, 2015 14:14
Show Gist options
  • Save hellomedia/048906b9449463cd5792 to your computer and use it in GitHub Desktop.
Save hellomedia/048906b9449463cd5792 to your computer and use it in GitHub Desktop.
Symfony2 link with POST Twig
<html>
<a href="{{ path('secure_route', {'id': foo.id }) }}" data-method="POST" data-csrf="{{ csrf_token('foo') }}">submit</a>
<script>
/**
* POST/PUT/DELETE with link
* create a form with given HTTP method
* Add CSRF token
* Append and submit
*/
$("a[data-method]").click(function(e) {
var $form = $('<form/>').hide();
$form.attr({
'action' : $(this).attr('href'),
'method': $(this).data('method')
})
// extra _method param for browsers who don't support PUT/DELETE (Symfony specific)
$form.append($('<input/>',{
type:'hidden',
name:'_method'
}).val($(this).data('method')));
if ($(this).data('csrf')) {
$form.append($('<input/>',{
type: 'hidden',
name: '_token'
}).val($(this).data('csrf')));
}
$(this).parent().append($form);
$form.submit();
return false;
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment