1

I am trying to "sort" hierarchically the options of a select using a bootstrap plugin that needs to identify the "order" of each item.

In view of this, I performed a database search to bring only the order of each of the items listed in select, put them inside an array set in twig and am trying to set each value of that array for each of the options.

Note: I am trying to use this plugin https://neofusion.github.io/hierarchy-select/index.html#

{% set ordem = [] %}
{% for item in cPublicaItemEstruturas %}
    {% if item not in ordem %}
        {% set ordem = ordem|merge([item.ordem]) %}
    {% endif %}
{% endfor %}

{% for i in ordem %}
    {{ i }}<!--Results in 1 1 1 1 2 3 2 3 1 2 3 1 2 1 2 3 4 1-->
    <script>
        $('#c_publica_item_estrutura_itemPai option').attr('data-level', '{{ i }}');
    </script>
{% endfor %}

I expected something like this:

console.log($('#c_publica_item_estrutura_itemPai option').attr('data-level', 1));
console.log($('#c_publica_item_estrutura_itemPai option').attr('data-level', 2));
console.log($('#c_publica_item_estrutura_itemPai option').attr('data-level', 3));
console.log($('#c_publica_item_estrutura_itemPai option').attr('data-level', 2));
console.log($('#c_publica_item_estrutura_itemPai option').attr('data-level', 3));
console.log($('#c_publica_item_estrutura_itemPai option').attr('data-level', 1));

But they all come out with only the first array index that is the 1.

0

1 Answer 1

1

The way you are doing is not working because at each iteration of {% for i in ordem %}, you are setting the current index value to all select options. You get data-level="1" for all not because it stops at first iteration, but because the value of the last index of ordem is 1.

You just need to change your code a little bit:

{% set ordem = [] %}
{% for item in cPublicaItemEstruturas %}
    {% if item not in ordem %}
        {% set ordem = ordem|merge([item.ordem]) %}
    {% endif %}
{% endfor %}

//changes start here
<script>
    var ordem = {{ ordem|json_encode }};
    var i = 0;
    $('#c_publica_item_estrutura_itemPai > option').each(function() {
        $(this).attr('data-level', test[i]);
        i++;
    });
</script>

See what I'm doing here?

1- I pass ordem to a javascript array;
2- I iterate over select options;
3- For each option I set data-level with the value of the current index of the array.

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

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.