Reputation: 491
I want to raise an issue that arose me and do not know how to fix it . Suppose I want to create a dynamic select , ie , if a select product , if I add or remove a product, select automatically updated. for example, could make the query in the controller like this:
$products = $em->getRepository('MyBundle:Entity')->findAll();
Then render it in this way:
return $this->render('MyBundle:myfolder:mytwig.html.twig', array("products" => $products));
And finally in my template , create my select like this:
<select>
{% for product in products %}
<option value="{{ product.name }}">{{ product.name }}</option>
{% endfor %}
</select>
my problem is I have a select where the user chooses to buy a product , and if you want to add another , by a button labeled "Add" enable a javascript , and so another select where you can choose another product is generated.
I've already made the javascript file, but if I use a twig for in the product not recognize me , ie , I can not add this with javascript:
<select>
{% for product in products %}
<option value="{{ product.name }}">{{ product.name }}</option>
{% endfor %}
</select>
long time since I am with this, please , if you can help me do . thanks
Upvotes: 2
Views: 433
Reputation: 813
I think that including your Javascript in your Twig file, and not in a separate file, enables you to use {{ }}
, resolving your problem.
Hope this helps.
Upvotes: 0
Reputation: 30416
You could do this with JavaScript alone, if you change your template to generate a "base" copy of your <SELECT>
like this (assuming jQuery for brevity):
<div id='products_list'>
<select>
{% for product in products %}
<option value="{{ product.name }}">{{ product.name }}</option>
{% endfor %}
</select>
</div>
<button id='AddProduct'>Add</button>
<script>
$('#AddProduct').on('click', function () {
var base = $('#products_list select:first');
base.parent().append(base.clone());
});
</script>
(demo)
Upvotes: 1