Tschallacka
Tschallacka

To delete an item, from a list you need a button that will allow you to delete it.

I place this one in authorname\pluginname\controllers\controllername\_list_toolbars.htm

<button
        class="btn btn-default oc-icon-trash-o"
        disabled="disabled"
        onclick="$(this).data('request-data', {
            checked: $('.control-list').listWidget('getChecked')
        })"
        data-request="onDelete"
        data-request-confirm="<?= e(trans('authorname.pluginname::lang.misc.sure')); ?>"
        data-trigger-type="enable"
        data-trigger=".control-list input[type=checkbox]"
        data-trigger-condition="checked"
        data-stripe-load-indicator>
        <?= e(trans('authorname.pluginname::lang.misc.remove')); ?>
    </button>

In authorname\pluginname\controllers\controllername\config_list.yaml we allow checkboxes

# Display checkboxes next to each record
showCheckboxes: true

Then in the controller we add the following function to actually delete what we want to delete

/** Delete items from the list. Ajax call **/
public function onDelete() {
    /** Check if this is even set **/
    if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {
        /** cycle through each id **/
        foreach ($checkedIds as $objectId) {
            /** Check if there's an object actually related to this id
                * Make sure you replace MODELNAME with your own model you wish to delete from.
              **/
            if (!$object = MODELNAME::find($objectId))
                continue; /** Screw this, next! **/
            /** Valid item, delete it **/
            $object->delete();
        }

    }
    /** Return the new contents of the list, so the user will feel as if
      * they actually deleted something
      **/
    return $this->listRefresh();
}

By calling $this->listRefresh() at the end you force the list to refresh what the user sees, without reloading the entire page.

Last updated

Scott
Scott

Also, if anyone wants it there is a composer package that you can pull in to add this functionality to all of your controllers.

https://github.com/october-widgets/list-delete

Surahman
Surahman

Thanks, very usefull!

wvllvw
wvllvw

change the button by this


<button

    class="btn btn-default oc-icon-trash-o"

    disabled="disabled"

    onclick="$(this).data('request-data', {

    checked: $('.control-list').listWidget('getChecked')

    })"

    data-request="onDelete"

    data-request-confirm="<?= e(trans('rainlab.user::lang.users.delete_selected_confirm')) ?>"

    data-trigger-action="enable"

    data-trigger=".control-list input[type=checkbox]"

    data-trigger-condition="checked"

    data-request-success="$(this).prop('disabled', true)"

    data-stripe-load-indicator>

   <?= e(trans('backend::lang.list.delete_selected')) ?>

   </button>
mcMraak
mcMraak

Thank you, it works!

1-5 of 5