1

I have this in my entry form:

        {{ csrfInput() }}
        {{ actionInput('entries/save-entry') }}
        {{ hiddenInput('entryId', entry.id) }}
        {{ hiddenInput('fields[questions][sortOrder][]', 'new:1') }}
        {{ hiddenInput('sectionId', section.id) }}
        {% namespace "fields[questions][blocks][new:1]" %}
        {{ hiddenInput('type', 'question') }}
        <div>
            <label for="question">Question</label>
            <input
                type="text"
                name="fields[question]"
                id="question"
                value="…"
            >
        </div>
        {% endnamespace %}

This is working fine for saving a new matrix block, but if I then want to resubmit and save more blocks, it's not creating new blocks, but overwriting the data of the existing one.

What do I need to change for it to save new blocks as well?

1 Answer 1

3

The old blocks are likely being discarded due to the way Craft handles “delta saves” for complex fields like Matrix.

This section of the Matrix field documentation should help you persist existing blocks!

{# Output existing block IDs to keep them around: #}
{% for blockId in entry.questions.anyStatus().ids() %}
  {{ hiddenInput('fields[questions][sortOrder][]', blockId) }}
{% endfor %}

{# Tell Craft about the new block: #}
{{ hiddenInput('fields[questions][sortOrder][]', 'new:1') }}

{# Output your fields, as you are now! #}

You do not need to POST all the existing fields back to persist the blocks—as long as their IDs are in the sortOrder array, Craft will leave them as-is!

💡 You can also insert the block at the beginning by placing the new:1 input before the existing block IDs.

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.