1

The below code doesn't appear to be working for me, it will delete all other blocks apart from itself. I just need it to delete itself.

trophyOrders is the Matrix field in the user account.

{% set orders = user.trophyOrders.all() %}

{# Loop through orders #}
{% for order in orders %}
<form method="post" accept-charset="UTF-8" id="form-{{ order.id }}" class="f-left">
{{ csrfInput() }}
{{ actionInput('users/save-user') }}
{{ redirectInput('account/manage-trophies?msg=entry-deleted') }}
{{ hiddenInput('userId', currentUser.id) }}
                                                        
{{ hiddenInput('fields[trophyOrders][sortOrder][]', order.id) }}
{{ hiddenInput('fields[trophyOrders][blocks][' ~ order.id ~'][type]', '0') }}

<button type="submit" class="btn-unstyled"><i class="fal fa-trash-alt"></i></button>                          
</form>
{% endfor %}

Thanks

1 Answer 1

1

I'm not sure how that code is supposed to work. The sortOrder controls which blocks (both existing and new) get saved in what order. The input in your form includes only the ID of the current block in the loop, so it makes sense that all other blocks will be deleted.

You want to achieve the opposite – keep all blocks except the current block in the loop. So you need to output a sortOrder that includes all existing IDs except the current one.

This code should work:

{% set orders = user.trophyOrders.all() %}
{% set ids = orders|column('id') %}

{% for order in orders %}
    <form method="post" accept-charset="UTF-8">
        {{ csrfInput() }}
        {{ actionInput('users/save-user') }}
        {{ hiddenInput('userId', currentUser.id) }}

        {% for id in ids|filter(id => id != order.id) %}
            {{ hiddenInput('fields[trophyOrders][sortOrder][]', id) }}
        {% else %}
            {{ hiddenInput('fields[trophyOrders][sortOrder][]', null) }}
        {% endfor %}

        <button type="submit" class="btn-unstyled">Delete order {{ order.id }}</button>
    </form>
{% endfor %}
3
  • I added an else statement for when it's the last block, which seems to work. Thanks for your help, again. {% else %} {{ hiddenInput('fields[trophyOrders][sortOrder][]', null ) }}
    – Mark
    Apr 19 at 8:18
  • @Mark Ah right, something like that would be required to remove the last matrix block, good catch!
    – MoritzLost
    Apr 19 at 8:32
  • I've added the else statement to my example code, in case someone is looking for a full example.
    – MoritzLost
    Apr 19 at 8:36

Your Answer

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

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