masugadesign / lab-reports-craft-cms

Other
2 stars 1 forks source link

Display related data #3

Closed angieherrera closed 1 year ago

angieherrera commented 1 year ago

Perhaps this is more of an issue of not fully grokking some more advanced concepts in Twig templating, but I'm unclear on how I can display related data for a particular element/object.

In my particular use case, I want to generate a report that shows a list of users and the data from a table in their "profile". The table is just a simple Table field in Craft and it can have any number of rows.

My hope is that the resulting report would show the table column as a list of the related table data, either separated by a comma or line break.

Here's a screenshot of example data that I pulled using Twig how I would normally use it in a front-end template. The "tasks" column is a list of key value pairs (task and status). CleanShot 2023-04-13 at 11 33 10

benjaminkohl commented 1 year ago

In each of these examples, is it just one row of the table data appearing in the right column? I'm trying to envision how this could be constructed so that any number of table rows could be placed in the same cell of the report.

benjaminkohl commented 1 year ago

I'm not sure if this is what you are looking for but I came up with the following. I hard-coded the attribute names rather than building it programmatically since Craft Table fields have the redundant "col#" keys in that array.

Screenshot 2023-04-13 at 3 15 28 PM

{% for user in users %}
    {% set tableFieldCellArray = [] %}
    {% for row in user.myTable %}
        {% set rowText = "Color: #{row.color}\nShape: #{row.shape}\nFlavor: #{row.flavor}\n"  %}
        {% set tableFieldCellArray = tableFieldCellArray|merge([rowText]) %}
    {% endfor %}

    {% set rows = rows|merge([[
        user.id,
        user.email,
        tableFieldCellArray|join('\n')
    ]]) %}
{% endfor %}

This Twig code resulted in this:

Screenshot 2023-04-13 at 3 20 57 PM

angieherrera commented 1 year ago

That is exactly what I was looking for. I was close but missed the join! Thanks so much!!

benjaminkohl commented 1 year ago

I'm happy that solved it for you!