AjaxAddToCartPopupSubscriber.php in Commerce Ajax Add to Cart 8
File
modules/dc_ajax_add_cart_popup/src/EventSubscriber/AjaxAddToCartPopupSubscriber.php
View source
<?php
namespace Drupal\dc_ajax_add_cart_popup\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\commerce_cart\Event\CartEntityAddEvent;
use Drupal\commerce_cart\Event\CartEvents;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Url;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class AjaxAddToCartPopupSubscriber implements EventSubscriberInterface {
protected $purchasedEntity;
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
public function onResponse(FilterResponseEvent $event) {
$response = $event
->getResponse();
if (!$this->purchasedEntity) {
return;
}
if (!$response instanceof AjaxResponse) {
return;
}
$view_builder = $this->entityTypeManager
->getViewBuilder('commerce_product_variation');
$product_variation = $view_builder
->view($this->purchasedEntity, 'dc_ajax_add_to_cart_popup');
$content = [
'#theme' => 'dc_ajax_add_cart_popup',
'#product_variation' => $product_variation,
'#product_variation_entity' => $this->purchasedEntity,
'#cart_url' => Url::fromRoute('commerce_cart.page')
->toString(),
];
$title = '';
$options = [
'width' => '700',
];
$response
->addCommand(new OpenModalDialogCommand($title, $content, $options));
$event
->setResponse($response);
}
public function onAddToCart(CartEntityAddEvent $event) {
$this->purchasedEntity = $event
->getEntity();
}
public static function getSubscribedEvents() {
return [
KernelEvents::RESPONSE => 'onResponse',
CartEvents::CART_ENTITY_ADD => 'onAddToCart',
];
}
}