0

I have an event subscriber that deducts a credit when someone makes a booking. If there are no credits left, how do I return a failure and stop the booking being made?

The subscriber is acting on ENTITY_INSERT.

public static function getSubscribedEvents(): array {
  return [
    EntityHookEvents::ENTITY_INSERT => [
      'redeemTicket',
      -20,
    ],
  ];
}

I've tried

throw new AccessDeniedHttpException('This booking needs a valid ticket!');

Although this results in a 'white screen'

Drupal\Core\Entity\EntityStorageException: This booking needs a valid ticket! in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (

Following the drupal event documentation.

9
  • What is the FQCN of EntityHookEvents?
    – cilefen
    Oct 18, 2023 at 2:34
  • Drupal\core_event_dispatcher\EntityHookEvents;
    – Interlated
    Oct 18, 2023 at 2:54
  • What is the Drupal version and what is the origin of the core_event_dispatcher module?
    – cilefen
    Oct 18, 2023 at 8:11
  • 2
    What do you expect to happen when throwing AccessDeniedHttpException in the middle of an SQL operation?
    – Hudri
    Oct 18, 2023 at 8:31
  • Probably worth noting that hook_entity_insert() runs once the entity has been stored. So there’s nothing to stop at that point. You probably want to listen for a presave event or hook_entity_create instead
    – Clive
    Oct 18, 2023 at 16:02

1 Answer 1

1

Yes, it's better to stop the save operation as soon as possible, but in this case, storing a content entity via SQL, the result is the same. Both hooks are in one SQL transaction, only that in the original code the SQL database has more to rollback. It might be a better idea to check the condition when validating the input data and only throw exceptions in database operations if anything unexpected happens.

BTW this is not a Symfony topic because you are using events dispatched from Drupal hooks. So it's the same as if you would put the code directly in these hooks. The referenced documentation is about events dispatched by the Symfony kernel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.