Edit

The Edit Crud Action will update an existing record if the request is POST or PUT and the data validates - otherwise it will attempt to render a form to the end-user.

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.

view

Get or set the view file to render at the end of the request.

The view setting is passed directly and unmodified to Controller::render().

To get the current configured view call the view method without any arguments.

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

To change the view to render, pass a string as first argument.

$this->Crud->action()->view('my_custom_view');

Note

If the first parameter is NULL - which is the default value - the normal CakePHP behavior will be used.

Warning

Due to the nature of this method, once a custom view has been set, it’s not possible to revert back to the default behavior by calling ->view(null) as it will return the current configuration.

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');

saveMethod

The method to execute on Table:: when saving an entity - the default value is save.

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

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

To change the saveMethod value pass an string argument to the method

$this->Crud->action()->saveMethod('my_custom_save_method');

saveOptions

The 2nd parameter to Table::save() - the default value is ['validate' => true, 'atomic' => true].

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

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

To change the saveOptions value pass an array argument to the method

$this->Crud->action()->saveOptions(['atomic' => false]);

Sometimes you need to change the accessible fields before you update your entity.

$this->Crud->action()->saveOptions(['accessibleFields' => ['role_id' => true]]);

serialize

Note

This setting is only relevant if you use the API listener.

Note

The API listener will always enforce success and data to be part of the _serialize array.

This method is intended to allow you to add additional keys to your API responses with ease. An example of this is the API Query Log.

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

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

To change the serialize keys, pass a string or an array as first argument.

If a string is passed, it will be cast to array automatically.

$this->Crud->action()->serialize(['my', 'extra', 'keys']);

relatedModels

Note

If you have the RelatedModels listener configured, you can have Crud automatically load related data.

<?php
$this->Crud->listener('relatedModels')->relatedModels(true);

Find out more about the RelatedModels listener in the Listeners chapter.

Events

This is a list of events emitted from the Edit Crud Action.

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.beforeFind

The event is emitted before calling the find method in the table.

The Crud Subject contains the following keys:

  • id The ID that was originally passed to the action and usually the primary key value of your table.
  • 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.

This is the last place you can modify the query before it’s executed against the database.

Note

An example

Given the URL: /posts/view/10 the repository object will be an instance of PostsTable and the query includes a WHERE condition with Posts.id = 10

After the event has emitted, the database query is executed with LIMIT 1.

If a record is found the Crud.afterFind event is emitted.

Warning

If no record is found in the database, the recordNotFound event is emitted instead of Crud.afterFind.

Add Conditions

public function delete($id)
{
    $this->Crud->on('beforeFind', function(\Cake\Event\EventInterface $event) {
        $event->getSubject()->query->where(['author' => $this->Auth->user('id')]);
    });

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

Crud.afterFind

After the query has been executed, and a record has been found this event is emitted.

The Crud Subject contains two keys:

  • id The ID that was originally passed to the action and is usually the primary key of your model.
  • entity The record that was found in the database.

Note

If an entity is not found, the RecordNotFound event is emitted instead.

Logging the Found Item

public function delete($id)
{
    $this->Crud->on('afterFind', function(\Cake\Event\EventInterface $event) {
        $this->log("Found item: " . $event->getSubject()->entity->id . " in the database");
    });

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

Crud.beforeSave

Note

Do not confuse this event with the beforeSave callback in the ORM layer

Called right before calling Table::save().

The Crud Subject contains the following keys:

  • entity An entity object marshaled with the HTTP POST data from the request.
  • saveMethod A string with the saveMethod.
  • saveOptions An array with the saveOptions.

All modifications to these keys will be passed into the Table::$saveMethod.

Warning

After this event has been emitted, changes done through the $action->saveMethod() or $action->saveOptions() methods will no longer affect the code, as the rest of the code uses the values from the Crud Subject

Crud.afterSave

Note

Do not confuse this event with the afterSave callback in the ORM layer.

This event is emitted right after the call to Table::save().

The Crud Subject contains the following keys:

  • success indicates whether or not the Table::save() call succeed or not.
  • created true if the record was created and false if the record was updated.
  • entity An entity object marshaled with the HTTP POST data from the request and the save() logic.

Check Created Status

public function edit($id)
{
    $this->Crud->on('afterSave', function(\Cake\Event\EventInterface $event) {
        if ($event->getSubject()->created) {
            $this->log("The entity was created");
        } else {
            $this->log("The entity was updated");
        }
    });

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

Check Success Status

public function edit($id)
{
    $this->Crud->on('afterSave', function(\Cake\Event\EventInterface $event) {
        if ($event->getSubject()->success) {
            $this->log("The entity was saved successfully");
        } else {
            $this->log("The entity was NOT saved successfully");
        }
    });

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

Get Entity ID

public function add()
{
    $this->Crud->on('afterSave', function(\Cake\Event\EventInterface $event) {
        if ($event->getSubject()->created) {
            $this->log("The entity was created with id: " . $event->getSubject()->entity->id);
        }
    });

    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.

Crud.beforeRender

Invoked right before the view will be rendered.

This is also before the controllers own beforeRender callback.