2

For the life of me I can't seem to find an answer for this question, so here goes!

I have a field called jobCounty in a section called jobs.

The jobCounty is selected in the CP from a drop down list I've created of english county names.

There are about 30 entries each with most with different county names, but some repeat the same county name.

I want to create a form select, with options that are populated by the jobCounty names that have been selected, but avoid repeats. Ideally in alphabetical order.

This question seems to feel like it might be answering the same question but for for a different purpose.

Related entries from a dynamic dropdown

Any help much appreciated

  • Stephen
| improve this question | | | | |
3

You are using a dropdown field, so you can't query for the counties in use directly from the database. (This would be possible if you had chosen to use categories or tags for them.)

But what you can do is to loop all your jobs entries to collect their respective counties.

{% set entries = craft.entries.section('jobs').limit(null) %}

{% set counties = [] %}
{% for entry in entries %}
    {% set counties = counties|merge({
        (entry.county.value): entry.county.value
    }) %}
{% endfor %}

{% set counties = counties|sort %}

Saving the county name also to the key of each array element makes sure you won't end up getting duplicates. When done use the sort filter to sort the list alphabetically.

Update: there seems to be a problem with getting the dropdown value with entry.county (the shortcut to get the value / calls the field models __toString method) when setting an array key, changing it to entry.county.value works.

| improve this answer | | | | |
  • Thanks Carlcs, I'll try this later tonight. Much appreciated! – Pathfinder Oct 8 '15 at 14:16
  • Hi Carlcs, this seem to be working (I changed county to the jobCounty field name), but how do I now loop through the counties to display them? I tried this: {% for county in counties %} <p>{{county}}</p> {% endfor %} Derping a lot lately. Many thanks. – Pathfinder Oct 12 '15 at 10:39
  • A big thanks to Carl, who contacted me directly via slack to help me with this one. We went through the issue and figured out the issue. He updated the post to reflect the fix. Very grateful for his time and support. Thanks! – Pathfinder Oct 12 '15 at 11:37

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.