2

I am creating a mad libs type of global. My global set is actually called madLibs.

Within that set, is a matrix field - that can have unlimited blocks. Each block only has two fields. actualRole and pretendRole.

What I have is working - but sometimes I might get the actualRole from one matrix, and the pretendRole from another. Ideally, I'd like to get the same fields from the same random matrix.

{# Get all of the matrix blocks for the global set #}
{% set globalSet = craft.globals.getSetByHandle('madLibs') %}

{% if globalSet|length %}

    {# Find out how many matrix blocks exist #}
    {% set madLibsCount = globalSet.madLib|length %} // 2

    {# Generate a random array key. Remember array is zero based #}
    {% set range = range(0, (madLibsCount - 1)) %}

    <h1>{{ globalSet.madLib[random(range)].actualRole }}</h1>
    <p>{{ globalSet.madLib[random(range)].pretendRole }}</p>
{% endif %}

Sometimes, this is happening:

<h1>{{ globalSet.madLib[0].actualRole }}</h1>
<p>{{ globalSet.madLib[1].pretendRole }}</p>

I would really like to have this each time:

<h1>{{ globalSet.madLib[0].actualRole }}</h1>
<p>{{ globalSet.madLib[0].pretendRole }}</p>

Thank you for any suggestions!

2

You need to create a common reference to the random number you are creating. Otherwise, you are getting a random number twice - and it's just luck that they show up as expected.

Try this:

{# Get all of the matrix blocks for the global set #}
{% set globalSet = craft.globals.getSetByHandle('madLibs') %}

{% if globalSet|length %}

    {# Find out how many matrix blocks exist #}
    {% set madLibsCount = globalSet.madLib|length %} // 2

    {# Generate a random array key. Remember array is zero based #}
    {% set range = range(0, (madLibsCount - 1)) %}

    {# Capture a single (random) number #}
    {% set key = random(range) %}

    <h1>{{ globalSet.madLib[key].actualRole }}</h1>
    <p>{{ globalSet.madLib[key].pretendRole }}</p>
{% endif %}

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.