member type automaticly filled on checkout

This commit is contained in:
2021-07-16 20:12:10 +02:00
parent 6cc3844230
commit e79bdeb5e6
8 changed files with 864 additions and 99 deletions

View File

@@ -0,0 +1,5 @@
services:
materio_commerce.order_events_subscriber:
class: Drupal\materio_commerce\EventSubscriber\MaterioCommerceOrderEventsSubscriber
tags:
- { name: 'event_subscriber' }

View File

@@ -0,0 +1,81 @@
<?php
// https://docs.drupalcommerce.org/commerce2/developer-guide/orders/workflows/react-to-workflow-transitions
namespace Drupal\materio_commerce\EventSubscriber;
use Drupal\commerce_order\Event\OrderEvent;
use Drupal\commerce_order\Event\OrderEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Class EntityTypeSubscriber.
*
* @package Drupal\custom_events\EventSubscriber
*/
class MaterioCommerceOrderEventsSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*
* @return array
* The event names to listen for, and the methods that should be executed.
*/
public static function getSubscribedEvents() {
return [
OrderEvents::ORDER_PAID => 'onOrderPaid'
// OrderEvents::ORDER_CREATE => 'onOrderCreate'
// 'commerce_order.order.paid' => ['onOrderPaid', -100]
];
}
public function onOrderPaid(OrderEvent $event) {
$order = $event->getOrder();
$customer = $order->getCustomer();
foreach ($order->getItems() as $order_item) {
// Skip order items that do not have a license reference field.
// We check order items rather than the purchased entity to allow products
// with licenses to be purchased without the checkout flow triggering
// our synchronization. This is for cases such as recurring orders, where
// the license entity should not be put through the normal workflow.
// Checking the order item's bundle for our entity trait is expensive, as
// it requires loading the bundle entity to call hasTrait() on it.
// For now, just check whether the order item has our trait's field on it.
// @see https://www.drupal.org/node/2894805
if (!$order_item->hasField('license')) {
continue;
}
$purchased_entity = $order_item->getPurchasedEntity();
// This order item isn't "licensable" if the purchased entity it
// references isn't properly configured.
if (!$purchased_entity->hasField('license_type') || $purchased_entity->get('license_type')->isEmpty()) {
continue;
}
$sku = $purchased_entity->getSku();
switch ($sku) {
case 'web-monthly':
case 'web-annual':
$member_type = 0;
break;
case 'web-showroom-monthly':
case 'web-showroom-annual':
$member_type = 1;
break;
}
}
if(isset($member_type)){
$customer->set('field_member_type', $member_type);
$customer->save();
}
// \Drupal::messenger()->addStatus('HAHA Order '.$order->getOrderNumber().' paid: ' . $customer->getEmail());
}
// public function onOrderCreate(OrderEvent $event) {
// $order = $event->getOrder();
// $customer = $order->getCustomer();
// \Drupal::messenger()->addStatus('HAHA Order '.$order->getOrderNumber().' created: ' . $customer->getEmail());
// }
}