I implemented a custom service which listens to the add to cart event and redirects to checkout. However I still see the add to cart message. We need a way to disable that. And possibly making redirect to checkout easier.

The event subscriber needs

  public static function getSubscribedEvents() {
    $events = [
      CartEvents::CART_ENTITY_ADD => ['onProductAdded', 1000],
      KernelEvents::RESPONSE => ['checkRedirectIssued', -10]
    ];
    return $events;
  }

And then.

  public function onProductAdded(CartEntityAddEvent $event) {
    \Drupal::requestStack()->getCurrentRequest()->attributes->set('_checkout_redirect_url', Url::fromRoute('commerce_checkout.form', [
      'commerce_order' => $event->getCart()->id(),
    ])->toString());
  }
  /**
   * Checks if a redirect rules action was executed.
   *
   * Redirects to the provided url if there is one.
   *
   * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
   *   The response event.
   */
  public function checkRedirectIssued(FilterResponseEvent $event) {
    $request = $event->getRequest();
    $redirect_url = $request->attributes->get('_checkout_redirect_url');
    if (isset($redirect_url)) {
      $event->setResponse(new RedirectResponse($redirect_url));
    }
  }

Comments

mglaman created an issue. See original summary.

scotthooker’s picture

scotthooker’s picture

Is there any sense in the "Add to cart" label being a setting on the variation or store somewhere other than it is now?

jtolj’s picture

We needed to do something similar to implement a minimum quantity check, which if not met removes the added product from the cart. I moved the drupal_set_message() from the submitForm() handler to an event subscriber, which can then be stopped using $event->stopPropagation();

I'm not sure this is the best approach to allow preventing this message from appearing. In our case, we're removing the product from the cart, so stopping event propagation has no side effects. In your case, you would want other events to still fire.

Regardless the drupal_set_message() definitely doesn't belong where it is currently.

Patch attached...

mglaman’s picture

Status: Active » Needs review

jtolj thanks, this looks like right first step.

jtolj’s picture

Updated patch... I'd read some bad documentation on setting the priority of an event subscriber and also fixed reference to the event name to use the provided constant (CartEvents::CART_ENTITY_ADD).

mglaman’s picture

  1. +++ b/modules/cart/commerce_cart.services.yml
    @@ -26,3 +26,9 @@ services:
    +    arguments: ['@commerce_cart.cart_provider', '@string_translation']
    
    +++ b/modules/cart/src/EventSubscriber/CartEventSubscriber.php
    @@ -0,0 +1,59 @@
    +  use StringTranslationTrait;
    ...
    +  public function __construct(CartProviderInterface $cart_provider, TranslationInterface $string_translation) {
    ...
    +    $this->stringTranslation = $string_translation;
    

    We do not need to inject the translation service, using the trait is fine enough.

    Works for me. This is a pattern in core and prevents the trait from accessing \Drupal as a fallback.

  2. +++ b/modules/cart/commerce_cart.services.yml
    @@ -26,3 +26,9 @@ services:
    +      - { name: event_subscriber, priority: -255 }
    

    Do we really need to set such a low priority? I think omitting the priority is fine.

    End users can remove or adjust using a CompilerPass in their code if needed.

jtolj’s picture

Updated patch to remove hard-coded priority value.

mglaman’s picture

Thumbs up from me. jtolij can you put this patch as a pull request on https://github.com/drupalcommerce/commerce? If not, I can later today. We don't run our tests on DrupalCI (yet), only via GitHub + Travis

jtolj’s picture

jeroent’s picture

+1 For this change.

This change is AFAIS necessary for modules like Commerce add to cart confirmation

jeroent’s picture

Status: Needs review » Reviewed & tested by the community

Tried the patch and it was working as expected. Code also looks good so RTBC!

jantoine’s picture

Status: Reviewed & tested by the community » Needs review
StatusFileSize
new3.32 KB

Reroll

drugan’s picture

Also, the Add to cart message might be disabled like this:

https://gist.github.com/drugan/ae65acc2e552454fba14a2067c254a54#file-dru...

imyaro’s picture

@drugan please forget about the d7-style alters
Just override CartEventSubscriber class with your own one to allow disable message.
But as for me - it will be great to manage this via configuration

jeroent’s picture

I added a way to override the event subscriber on the PR#670.

heddn’s picture

Status: Needs review » Needs work

Let's add the dsm in an event subscriber. that way you can much more easily disable it. Working on that now.

heddn’s picture

Status: Needs work » Reviewed & tested by the community

Actually, I should look at the patch first. It does exactly what I was proposing/planning to do. RTBC.

heddn’s picture

For those not familiar with event subscribers, you can easily disable other events using the approach listed in https://symfony.com/doc/current/components/event_dispatcher.html#stoppin...

If you register your custom event before the one in this patch, you can simply disable propagation and effectively disable or change the dsm. Actually, it sounds like a great contrib module, build a method to override and/or disable the message via this cool new commerce_cart_message module!

joshmiller’s picture

A lot of work was made in a similar project, if the maintainers would see fit to give a little credit nod to sorab.v6 for his work there, that would be very classy.

#2905624: Need a simple alter hook for the add to cart message

bojanz’s picture

Status: Reviewed & tested by the community » Needs work

The event subscriber is injecting a cartProvider that is never used.

bojanz’s picture

Title: Allow add to cart message to be disabled » Move the add to cart message to an event subscriber to allow it to be replaced/removed
bojanz’s picture

Updating credits.

bojanz credited sorabh.v6.

bojanz’s picture

  • bojanz committed a3ef38d on 8.x-2.x authored by jtolj
    Issue #2834416 by jtolj, jantoine, mglaman, bojanz, heddn, JeroenT,...
bojanz’s picture

Status: Needs work » Fixed

Improved and committed. Thanks, everyone.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.