I need to generate url to be able to load some content in html element.
$('#editSchool').click(function () {
var id = $(this).attr('data-id');
Problem starts here when I try to insert id value for id parameter
$('#educationDialog').load("{{ path('_education_edit', {'id': id}) }}", function () {
$('.closeDialog, #person_education_form_cancel').click(function () {
$('#addSchool').trigger('click');
});
});
});
Do you have some solution, if this is possible?
I need to generate url to be able to load some content in html element.
$('#editSchool').click(function () {
var id = $(this).attr('data-id');
Problem starts here when I try to insert id value for id parameter
$('#educationDialog').load("{{ path('_education_edit', {'id': id}) }}", function () {
$('.closeDialog, #person_education_form_cancel').click(function () {
$('#addSchool').trigger('click');
});
});
});
Do you have some solution, if this is possible?
Share Improve this question asked Jan 6, 2017 at 11:12 Stevan TosicStevan Tosic 7,25913 gold badges65 silver badges120 bronze badges 1- Please state clearly the problem and desired behaviour. – Mitya Commented Jan 6, 2017 at 11:14
2 Answers
Reset to default 2The problem was very simple. Instead of passing data-id attribute, data-url can be passed.
<span id="editSchool" data-url="{{ path('_education_edit', {'id': id}) }}">
Edit School
</>
$('#editSchool').click(function () {
var url = $(this).data('url');
$('#educationDialog').load(url, function () {
$('.closeDialog, #person_education_form_cancel').click(function () {
$('#addSchool').trigger('click');
});
});
});
The twig is parsed when the page is rendered, so the id variable in your route declartion is set when the page loads.
The easiest fix is to change your route to accept a nullable parameter for the id, then add the id to the route in your JavaScript. Also, for use in JavaScript, you will need to use the url twig function as it gives an absolute url, path gives a relative url. Ref: What is the difference between 'url' and 'path' in symfony2.3
Example routing.yml;
my_route:
path: /foo/bar/{id}
defaults: { _controller: AppBundle:Foo:bar, id: null }
Then in your twig;
<script>
var url = '{{ url('my_route') }}'+'/';
var id = $(this).attr('data-id');
$('#educationDialog').load(url+id, function () {
// ...
});
</srcipt>