Bulk

If you need to perform an action against a number of records, you can extend the abstract Bulk\BaseAction class to create your own.

Three BulkAction classes exist in the core:

  • Delete: Deletes a set of entities
  • SetValue: Sets a field to a value for a set of entities
  • Toggle: Toggles the value of a boolean field for a set of entities

To create your own BulkAction, simply create a new action class with a _bulk method. This method takes a CakePHP Query object as its first argument

<?php
namespace App\Crud\Action;

use Cake\ORM\Query;
use Crud\Action\Bulk\BaseAction;

class ApproveAction extends BaseAction
{
  /**
   * Set the value of the approved field to true
   * for a set of entities
   *
   * @param \Cake\ORM\Query $query The query to act upon
   * @return boolean
   */
  protected function _bulk(Query $query)
  {
    $query->update()->set(['approved' => true]);
    $statement = $query->execute();
    $statement->closeCursor();
    return $statement->rowCount();
  }
}

Configuration

Note

Before applying any configuration to an action it must be mapped first.

If the action has not been mapped an exception will be raised.

enabled

Test or modify if the Crud Action is enabled or not.

When a CrudAction is disabled, Crud will not handle any requests to the action, and CakePHP will raise the normal \Cake\Error\MissingActionException exception if you haven’t implemented the action in your controller.

Warning

If you have enabled Crud and you are still receiving a MissingActionException, ensure the action is enabled and that the controller has the \Crud\Controller\ControllerTrait implemented.

To test if an action is enabled, call the enabled method on the action.

$this->Crud->action()->enabled();

To disable an action, call the disable method on the action.

$this->Crud->action()->disable();

To enable an action, call the enable method on the action.

$this->Crud->action()->enable();

To disable or enable multiple actions at the same time, Crud Component provides helper methods.

The enable and disable method can take a string or an array, for easy mass-updating.

$this->Crud->enable('index');
$this->Crud->enable(['index', 'add']);

$this->Crud->disable('index');
$this->Crud->disable(['index', 'add']);

Note

These methods simply calls the enable and disable method in each Crud Action class, and do not provide any magic other than mass updating.

Warning

While it’s possible to update the enabled property directly on an action using the config methods, it’s not recommend, as important cleanup logic will not be applied if you use the setConfig() method directly.

findMethod

The 1st parameter to Table::find() - the default value is all.

To get the current configured findMethod keys call the findMethod method without any arguments.

$this->Crud->action()->findMethod();

To change the findMethod value pass a string argument to the method

$this->Crud->action()->findMethod('my_custom_finder');

Events

This is a list of events emitted from actions that extend Bulk\BaseAction.

Please see the events documentation for a full list of generic properties and how to use the event system correctly.

Crud.startup

Called after the Controller::beforeFilter() and before the Crud action.

It’s emitted from CrudComponent::startup() and thus is fired in the same cycle as all Component::startup() events.

Crud.beforeFilter

Triggered when a CrudAction is going to handle a CakePHP request.

It’s emitted from CrudComponent::beforeFilter and thus is fired in the same cycle as all Controller::beforeFilter events.

Crud.beforeBulk

This event is emitted before _bulk() is called on a Bulk Crud action.

The Crud Subject contains the following keys:

  • ids A list of ids of entities, from the request data
  • repository An instance of the Repository (Table) which the query will be executed against.
  • query A Query object from the Repository where $PrimaryKey => $IdFromRequest is already added to the conditions.

To abort a bulk action, simply stop the event by calling $event->stopPropagation().

Stop Bulk Action

public function bulk($id)
{
    $this->Crud->on('beforeBulk', function(\Cake\Event\EventInterface $event) {
        // Stop the bulk event, the action will not continue
        if ($event->getSubject()->item->author !== 'admin') {
            $event->stopPropagation();
        }
    });

    return $this->Crud->execute();
}

Crud.afterBulk

This event is emitted after calling _bulk() on a Bulk Crud action.

The Crud Subject contains two keys:

  • success if true the _bulk() call succeeded, false otherwise
  • ids A list of ids of entities, from the request data
  • repository An instance of the Repository (Table) which the query will be executed against.
  • query A Query object from the Repository where $PrimaryKey => $IdFromRequest is already added to the conditions.

Check Success

public function bulk($id)
{
    $this->Crud->on('afterBulk', function(\Cake\Event\EventInterface $event) {
        if (!$event->getSubject()->success) {
            $this->log("Bulk action failed");
        }
    });

    return $this->Crud->execute();
}

Crud.setFlash

Simple and event driven wrapper for SessionComponent::setFlash.

The Crud Subject contains the following keys:

  • text The 1st argument to SessionComponent::setFlash.
  • element The 2nd argument to SessionComponent::setFlash.
  • params The 3rd argument to SessionComponent::setFlash.
  • key The 4th argument to SessionComponent::setFlash.
  • entity (Optional) The Entity from the previously emitted event.

All keys can be modified as you see fit, at the end of the event cycle they will be passed directly to SessionComponent::setFlash.

Defaults are stored in the messages configuration array for each action.

If you do not want to use this feature, simply stop the event by calling its stopPropagation() method.

If you’d like to customise the flash messages that are used, perhaps you’re using friendsofcake/bootstrap-ui. It’s actually quite simple to do, and can be done as part of the component configuration or on the fly.

public function initialize()
{
      $this->loadComponent('Crud.Crud', [
          'actions' => [
              'edit' => [
                  'className' => 'Crud.Edit',
                  'messages' => [
                      'success' => [
                          'params' => ['class' => 'alert alert-success alert-dismissible']
                      ],
                      'error' => [
                          'params' => ['class' => 'alert alert-danger alert-dismissible']
                      ]
                  ],
              ]
          ]
      ]);
}

If you’d like to configure it on the fly you can use the eventManager to change the event subject as the event is emitted.

$this->eventManager()->on('Crud.setFlash', function (Event $event) {
    if ($event->getSubject()->success) {
        $event->getSubject()->params['class'] = ['alert', 'alert-success', 'alert-dismissible'];
    }
});

Crud.beforeRedirect

Simple and event driven wrapper for Controller::redirect().

The Crud Subject contains the following keys:

  • url The 1st argument to Controller::redirect().
  • status The 2nd argument to Controller::redirect().
  • exit The 3rd argument to Controller::redirect().
  • entity (Optional) The Entity from the previously emitted event.

All keys can be modified as you see fit, at the end of the event cycle they will be passed directly to Controller::redirect().

The redirect $url can be changed on the fly either by posting a redirect_url field from your form or by providing a redirect_url HTTP query key.

The default for most redirects are simply to return to the index() action.