Last active
August 29, 2015 14:14
-
-
Save hellomedia/048906b9449463cd5792 to your computer and use it in GitHub Desktop.
Symfony2 link with POST Twig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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