Skip to content

Override DELETE operation: update status property instead #291

@cookingfox

Description

@cookingfox

Hi!

I want to override all entities' DELETE operation with a custom implementation that sets a new value to a custom status property instead. For example, when I do DELETE /api/projects/3 I want it to set the status property of the Project entity with ID 3 to value disabled, and NOT remove the record from the database. I want to apply this to all my entities - they all implement a base EntityInterface that contains the getter + setter for this status property.

I spent some time trying the options I could think of, with the following results:

  1. Create a custom operation

The problem I ran into is routing: I want to use this for all my entities, but could not figure out how to have a dynamic route in the action, e.g.:

class SafeDeleteEntity
{
    /**
     * @Route(
     *     name="safe_delete_entity",
     *     path="/{entity}/{id}",
     *     defaults={"_api_resource_class"=EntityInterface::class, "_api_item_operation_name"="safe_delete_entity"}
     * )
     * @Method("DELETE")
     */
    public function __invoke($data) { ... }
}

Usage in entity:

/**
 * @ORM\Entity
 * @ApiResource(
 *     itemOperations={
 *          "delete"={"method"="DELETE", "route_name"="safe_delete_entity"}
 *     }
 * )
 */
class MyEntity implements EntityInterface { ... }

This would result in a 405 error: method DELETE not allowed.

  1. Hook into the event system

I was able to hook into the PRE_WRITE kernel event and check the entity and operation. I understand this is where I can update the entity status property, but I could not figure out how to prevent the DELETE operation. Is this even possible this way?

  1. Create a custom extension

When printing the query builder, it was for the SELECT operation, not DELETE. It sounds logical that we first want to check whether there is an entity with the requested ID to provide the user with a 404 error when it does not. However, if this is not the DELETE operation, then it appears I am not able to override it this way...

Can you please advise me on the correct way to implement this?

Thanks!

Abel
Cooking Fox

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions