2

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

1
  • That arose you ? not sure you wanted to say that ... Commented Jun 17, 2015 at 8:05

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.