lewisjenkins / craft-dynamic-fields

Populate Craft fields with dynamic data using the power of Twig.
Other
147 stars 11 forks source link

Example: Populate with sibling matrix block IDs. #20

Open swthate opened 6 years ago

swthate commented 6 years ago

Not an issue, but excited to share I finally figured out how to make a dropdown inside a matrix field that gets populated with the IDs of sibling blocks:

{# Get ID of entry currently editing #}
{% set segment = craft.app.request.getSegment(3)|split('-') %}
{% set theEntryId = segment[0] %}

{# Query the entry and loop through its matrix field, if populated #}
{% set theEntry = craft.entries.id(theEntryId).one() %}
{% if theEntry.matrixField|length %}
    {% for block in theEntry.matrixField %}
        {{ loop.index > 1 ? ',' }} {
            "value":"{{block.id}}",
            "label":"{{block.siblingBlockLabelFriendlyField}}"
        }
    {% endfor %}
{% endif %}

This isn't much of an issue, but it took me a little bit to figure out. I'm not sure if it is mentioned explicitly anywhere in your readme, but I was only able to fix an "invalid foreach argument" error by including the {{ loop.index > 1 ? ',' }} bit before the value/label block inside a for loop that I finally noticed in some of your examples. Maybe a nod to that for dynamic fields within a loop?

Anyway, awesome plugin!!

swthate commented 6 years ago

Something I just thought of: how can I include an option at the top of the list with a NULL value?

I placed this ahead of my for loop:

{
    "value":null,
    "label":"None"
},

I tried both null and "null" but is not null doesn't work on it. I suppose I could just test against the presence of a particular string value?

lewisjenkins commented 6 years ago

Have you tried:

{
    "value":"",
    "label":"Please select..."
}
swthate commented 6 years ago

This is weird, when I print the field, {{ block.replaces }}, it returns the length of the stored string, which after dumping it I can tell is the correct block id.

Why is it printing the length of the string and not the string itself? Hmm

Update:

Wow, I don't know what's going on, but I deleted my dump() stuff and now it's printing out the actual id of the selected block... No idea what I did. I think it's time for a break, lol!