1

I am trying to use some Twig code to sort entries by a date field that is contained within a Venti field. Here is the code:

{% set allWorkshops = [] %}
{% for entry in craft.entries.section('workshop') %}

            {% set event = craft.venti.getEventById(entry.id) %}    {# get the Venti array for each entry #}    

            {% set eventDate = event.startDate %}  {# get the Venti date field #}


            {% set allWorkshops = allWorkshops|merge({ 
                    'eventDate' : event.startDate,
                    'name' : entry.title                    
                }) %}                               {# merge combined date and title into array #}

{% endfor %}

{% for item in allWorkshops|sort %}
  <div>{{ item }}</div>
{% endfor %}

It works, except that the array 'allWorkshops' only contains the last item from the "entry" loop. Obviously 'allWorkshops' is getting overwritten for each iteration of the loop, but I do not understand why, given that it is defined outside the loop.

Thanks for any enlightenment!

2

What your merge filter does now, is merge the new object with the previous one, thus overriding the values for both keys.

Try this:

{% set allWorkshops = allWorkshops|merge([{ 
    'eventDate' : event.startDate,
    'name' : entry.title                    
}]) %}

Merging your existing array with a new array containing one object.

  • Of course! I had the feeling it was something obvious, but just not to me - thanks, Paul, will give that a try – Roi Agneta Apr 12 '18 at 22:10
0

The problem, as noted by Paul Verheul, is that the key:values created in each loop overwrites the previous one. The solution is to save each iteration as an object in a new array. The code now looks like this:

{% set allWorkshops = [] %} 
{% set workshop = [] %}

{% set workshops = craft.entries.section('workshop') %} {# get entries #}   

    {% for entry in workshops %}

                {% set event = craft.venti.getEventById(entry.id) %}    {# get the Venti array for each entry #}    

                {% set workshop = {
                        'eventDate' : event.startDate,
                        'eventTitle' : entry.title                  
                    } %}

                {% set allWorkshops = allWorkshops|merge([ workshop ]) %}

    {% endfor %}

    {% for item in allWorkshops|sort %}  {# sort items by eventDate #}
        <div>{{item.eventDate}} {{item.eventTitle}}</div>
    {% endfor %}

I also came across this answer which was in response to a different question but same basic issue: Create an object of objects with merge

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.