orchidsoftware / crud

Simplify the process of building CRUD (Create, Read, Update, Delete) functionality in Laravel using the features of Orchid.
https://orchid.software
MIT License
138 stars 34 forks source link

Bulk Actions #23

Closed tabuna closed 3 years ago

tabuna commented 3 years ago

Introduction

As mentioned here, it would be great to have action and bulk action for the CRUD. This PR is aimed at implementing such an idea. We already have examples of such an implementation in similar projects (https://litstack.io/docs/3.x/crud/actions and https://nova.laravel.com/docs/3.0/actions/defining-actions.html)

image

Proposed change

Actions may be generated using the orchid:action Artisan command:

php artisan orchid:action CustomAction

By default, all actions are placed in the app/Orchid/Actions directory.

The action necessarily consists of two methods. Method button defines name, icon, dialog box, etc. And the handler method directly handles the action with the models.

namespace App\Orchid\Actions;

use Illuminate\Support\Collection;
use Orchid\Crud\Action;
use Orchid\Screen\Actions\Button;
use Orchid\Support\Facades\Toast;

class CustomAction extends Action
{
    /**
     * The button of the action.
     *
     * @return Button
     */
    public function button(): Button
    {
        return Button::make('Run Custom Action')->icon('fire');
    }

    /**
     * Perform the action on the given models.
     *
     * @param \Illuminate\Support\Collection $models
     */
    public function handle(Collection $models)
    {
        $models->each(function () {
            // action
        });

        Toast::message('It worked!');
    }
}

Within the handle method, you may perform whatever tasks are necessary to complete the action.

The handle method always receives a Collection of models, even if the action is only being performed against a single model.

Once you have defined an action, you are ready to attach it to a resource. Each resource contains an actions method. To attach an action to a resource, you should add it to the array of actions returned by this method:

/**
 * Get the actions available for the resource.
 *
 * @return array
 */
public function actions(): array
{
    return [
        CustomAction::class,
    ];
}