1

I'm building a site that contains a listing of products and distributors. I have a channel for each, and each entry in the distributors channel contains a relationship field to tie it to any number of entries in the products channel. There are about 20 entries in each channel.

I need to set up a page with a table that includes all of the products across the top, and all of the distributors in the left column, with a check box in each cell where there is a relationship between the two.

I know how to just use standard related entries tags to output the distributors and list out the related products for each, but is there a way get it into the table format, without a ridiculous number of queries?

1 Answer 1

2

Let me show you the quickest solution I could think of. If you put it in {% cache %} tags, you should be fine. You could also create a little plugin that returns the required data from one big-ass query, if you're into building plugins. If you have any plugin experience, then building a plugin is what I would do.

{% set distributors = craft.entries.section('distributors').limit(null) %}
{% set allRelatedProducts = craft.entries.section('products').relatedTo(distributors).limit(null) %}

<table>
    <thead>
        <tr>
            <th>Distributor</th>
            {% for product in allRelatedProducts %}
                <th>{{ product.title }}</th>
            {% endfor %}
        </tr>
    </thead>
    <tbody>
        {% for distributor in distributors %}
            {# Get ids for all products related to distributor #}
            {% set productsForDistributor = craft.entries.section('products').relatedTo(distributor).limit(null).ids() %}
            <tr>
                <td>{{ distributor.title }}</td>
                {% for product in allRelatedProducts %}
                    {# 
                     # Check if product ID is in array containing this distributor's products
                     # and display value accordingly
                     #}
                    <td>{{ product.id in productsForDistributor ? 'yes' : 'no' }}</td>
                {% endfor %}
            </tr>
       {% endfor %}
    </tbody>
</table>

Your Answer

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

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