Skip to content

Instantly share code, notes, and snippets.

@keopx
Forked from manojiksula/Drupal Commerce 2.md
Created March 21, 2024 20:08
Show Gist options
  • Save keopx/037fa0fda3f124f1111a341bfaa7e561 to your computer and use it in GitHub Desktop.
Save keopx/037fa0fda3f124f1111a341bfaa7e561 to your computer and use it in GitHub Desktop.

Drupal Commerce Code Snippet

Reference

Snippets -> https://www.drupal.org/documentation/customization/snippets
A beginner's guide to using snippets -> https://www.drupal.org/node/337959
Drupal Commerce 2 Snippets -> https://gist.github.com/jakubhnilicka/00ed4492fea86571ab88a68d0e7a2158
https://gist.github.com/BBGuy/c362a30bb0dda65777b076040b14cab5

Storage Code of Different Entities of Drupal Commerce

Store -> commerce_store
Product Variation -> commerce_product_variation_type
Product Type -> commerce_product_type

Store Snippet

Get Current Store Information

$current_store = \Drupal::service('commerce_store.current_store');
$store = $current_store->getStore();
dump($store);

Create store

$currency = 'INR';
$storeType = 'online';
$storeData = [
  'type' => $storeType,
  'uid' => 1,
  'name' => 'Sample Store Name',
  'mail' => '[email protected]',
  'address' => [
    'country_code' => 'IN',
    'address_line1' => 'Times Square, Marol Naka, Andheri(E)',
    'locality' => 'Mumbai',
    'administrative_area' => 'Maharashtra',
    'postal_code' => '400059',
  ],
  'default_currency' => $currency, // we can change the default currency of store
  'billing_countries' => ['IN']
];

$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_store');

// If needed, this will import the currency.
$currency_importer = \Drupal::service('commerce_price.currency_importer');
$currency_importer->import($currency);

$store = Store::create($storeData);
$store->save();

if($store) {
  $storage->markAsDefault($store); // If needed, this sets the store as the default store.
}

Load Store by "ID"

use Drupal\commerce_store\Entity\Store;

$storeId = 1;
$store = Store::load($storeId);

$email = $store->getEmail();
$name = $store->getName();
$address = $store->getAddress();
$currencyName = $store->getDefaultCurrency()->getName();

Load Store by "loadByProperties"

$storeType = 'online';
$storeName = "Eshop";
$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_store');
$stores = $storage->loadByProperties(['type' => $storeType, 'name' => $storeName]);
$store = reset($stores); // "reset" is used to get first index of array

$email = $store->getEmail();
$name = $store->getName();
$address = $store->getAddress();
$currencyName = $store->getDefaultCurrency()->getName();

Load Multiple Stores by store Ids

$storeType = 'online';
$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_store');
$stores = $storage->loadByProperties(['type' => $storeType]);
$storeIds = array_keys($stores);
$storesList = $storage->loadMultiple($storeIds);

foreach ($storesList as $store) {
    $email = $store->getEmail();
    $name = $store->getName();
    $address = $store->getAddress();
    $currencyName = $store->getDefaultCurrency()->getName();
}

Update stores

Update by "ID"

use Drupal\commerce_store\Entity\Store;

$storeId = 1;
$store = Store::load($storeId);

$store->setEmail('[email protected]');
$store->save();

Update stores by "loadByProperties"

$storeType = 'online';
$storeName = "Sample Store Name";
$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_store');
$stores = $storage->loadByProperties(['type' => $storeType, 'name' => $storeName]);
$storeIds = array_keys($stores);
$storesList = $storage->loadMultiple($storeIds);

foreach ($storesList as $store) {
  $store->setEmail('[email protected]');
  $store->save();
}

Delete Store

Delete by "ID"

use Drupal\commerce_store\Entity\Store;

$storeId = 1;
$store = Store::load($storeId);
$store->delete();

Delete by "loadByProperties"

$storeType = 'online';
$storeName = "Sample Store Name";
$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_store');
$stores = $storage->loadByProperties(['type' => $storeType, 'name' => $storeName]);
$storeIds = array_keys($stores);
$storesList = $storage->loadMultiple($storeIds);

foreach ($storesList as $store) {
  $store->delete();
}

List All stores

$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_store');
$stores = $storage->loadByProperties([]);

foreach ($stores as $store) {
  $email = $store->getEmail();
  $name = $store->getName();
  $address = $store->getAddress();
  $currencyName = $store->getDefaultCurrency()->getName();
}

Backend: Product Variations

Create Custom Product Variation

use Drupal\commerce_product\Entity\ProductVariationType;

// Create the new variation type.
$variationType = ProductVariationType::create([
  'status' => 1, // Status, 0 for disabled, 1 for enabled.
  'id' => 'variation_type_with_color',
  'label' => 'Variation Type With Color',
  'orderItemType' => 'default', // Order item type to reference. Default is 'default'.
  'generateTitle' => TRUE, // True to generate titles based off of attribute values.
]);
$variationType->save();

List all Product variations type

$variationStorage = \Drupal::service('entity_type.manager')->getStorage('commerce_product_variation_type');
$productVariations = $variationStorage->loadByProperties([]);
dump($productVariations);

Edit Product Variation types

Update by "ID"

use Drupal\commerce_product\Entity\ProductVariationType;

$typeId = 'variation_type_with_color';
$productVariationType = ProductVariationType::load($typeId);

$productVariationType->set('label','Variation Type With Color 2');
$productVariationType->save();

update by "loadByProperties"

use Drupal\commerce_product\Entity\ProductVariationType;

$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_product_variation_type');
$variationsTypes = $storage->loadByProperties(['status' => 1, 'label' => 'Default']);
$variationsType = reset($variationsTypes);

$variation = ProductVariationType::load($variationsType->id());
$variation->set('label', 'Default22');
$variation->save();

Delete Product variations type

$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_product_variation_type');
$productVariationTypes = $storage->loadByProperties(['label' => 'Variation Type With Color 2']);

foreach ($productVariationTypes as $productVariation) {
  $productVariation->delete();
}

Product Types

Create Custom Product Variation and types

Create Custom Product type

use Drupal\commerce_product\Entity\ProductType;
$variationTypeId = 'variation_type_with_color';

// Create the new product type.
$productType = ProductType::create([
  'id' => 'color_variations',
  'label' => 'Product Type with Color Variations',
  'status' => 1, // 0 for disabled, 1 for enabled
  'description' => 'This is the description of the product', // Optional
  'variationType' => $variationTypeId, // The variation type we want to reference for this
  'injectVariationFields' => TRUE, // Optional - defaults to true
]);
$productType->save();

List all Product types

$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_product_type');
$productTypes = $storage->loadByProperties([]);
dump($productTypes);

Edit Product types

update by "ID"

use Drupal\commerce_product\Entity\ProductType;

$typeId = 'color_variations';
$productType = ProductType::load($typeId);

$productType->set('label','updated label from code');
$productType->save();

update by "loadByProperties"

use Drupal\commerce_product\Entity\ProductType;

$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_product_type');
$productTypes = $storage->loadByProperties(['status' => 1, 'label' => 'Default']);
$productType = reset($productTypes);

$productType = ProductType::load($productType->id());

$productType->set('label', 'Default Manoj');
$productType->save();

Delete Product types

Delete by "ID"

use Drupal\commerce_product\Entity\ProductType;

$typeId = 'color_variations';
$productType = ProductType::load($typeId);
$productType->delete();

Delete by "loadByProperties"

$storage = \Drupal::service('entity_type.manager')->getStorage('commerce_product_type');
$productTypes = $storage->loadByProperties(['label' => 'updated label from code']);

foreach ($productTypes as $productType) {
  $productType->delete();
}

Product Attributes

Create Product Attributes

create product Attribute inside /admin/commerce/product-attributes attributes will be linked to product variations

$color_attribute = \Drupal\commerce_product\Entity\ProductAttribute::create([
      'id' => 'color',
      'label' => 'Color',
    ]);
    $color_attribute->save();

    $red = \Drupal\commerce_product\Entity\ProductAttributeValue::create([
      'attribute' => 'color',
      'name' => 'Red',
    ]);
    $red->save();

    $blue = \Drupal\commerce_product\Entity\ProductAttributeValue::create([
      'attribute' => 'color',
      'name' => 'Blue',
    ]);
    $blue->save();

    $medium = \Drupal\commerce_product\Entity\ProductAttributeValue::create([
      'attribute' => 'size',
      'name' => 'Medium',
    ]);
    $medium->save();

    $large = \Drupal\commerce_product\Entity\ProductAttributeValue::create([
      'attribute' => 'size',
      'name' => 'Large',
    ]);
    $large->save();

    $size_attribute = \Drupal\commerce_product\Entity\ProductAttribute::create([
      'id' => 'size',
      'label' => 'Size',
    ]);
    $size_attribute->save();

    // We load a service that adds the attributes to the variation type we made previously.
    $attribute_field_manager = \Drupal::service('commerce_product.attribute_field_manager');

    $variation_type_to_attach = 'default';
    $attribute_field_manager->createField($color_attribute, $variation_type_to_attach);
    $attribute_field_manager->createField($size_attribute, $variation_type_to_attach);

create product type Attributes inside /admin/commerce/config/product-types/default/edit attributes will be linked to products directly

// check if product attribute is already present or not

public function commerceProductHasField($field_name = "") {
  $bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('commerce_product');
  foreach($bundles as $bundle => $label) {
    $all_bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('commerce_product', $bundle);
    if (isset($all_bundle_fields[$field_name])) {
      return TRUE;
    }
  }
  return FALSE;
}

use Drupal\entity\BundleFieldDefinition;

$productType = 'default';
$attributes = [];
$attributes[] = [
  'type' => 'text_with_summary',
  'bundle' => $productType,
  'name' => 'description',
  'label' => 'Description'
];

$attributes[] = [
  'type' => 'string',
  'bundle' => $productType,
  'name' => 'plain_text222',
  'label' => 'Plain Text222'
];

$attributes[] = [
  'type' => 'file',
  'bundle' => $productType,
  'name' => 'file',
  'label' => 'File'
];

foreach ($attributes as $attribute) {
  $check_attribute = $this->commerceProductHasField(strtolower($attribute['name']));
  if(!$check_attribute) {
    $field_definition = BundleFieldDefinition::create($attribute['type'])
      ->setTargetEntityTypeId('commerce_product')
      ->setTargetBundle($attribute['bundle'])
      ->setName(strtolower($attribute['name']))
      ->setLabel($attribute['label'])
      ->setRequired(FALSE)
      ->setTranslatable(TRUE)
      ->setSetting('display_summary', FALSE);

    if($attribute['attribute_type'] == 'text_with_summary') {
      $field_definition->setDisplayOptions('form', [
        'type' => 'text_textarea_with_summary',
        'weight' => 1,
      ])
        ->setDisplayOptions('view', [
          'label' => 'hidden',
          'type' => 'text_default',
        ]);
    }

    if($attribute['attribute_type'] == 'string') {
      $field_definition->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 1,
      ])
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
      ]);
    }

    $configurable_field_manager = \Drupal::service('commerce.configurable_field_manager');
    $configurable_field_manager->createField($field_definition, FALSE);
  }
}

List all Product Attributes

$product_type = 'default';
$bundle_info = \Drupal::service('entity_type.bundle.info')->getBundleInfo('commerce_product');
$attributeList = \Drupal::service('entity_field.manager')->getFieldDefinitions('commerce_product', $product_type);
dump($attributeList);exit;

Edit Product Attributes

Delete Product Attributes

Checking if an attribute value exists within a particular attribute type

// Look up while filtering by Attribute
$productAttributeId = \Drupal::entityTypeManager()
    ->getStorage('commerce_product_attribute_value')
    ->getQuery()
    ->condition('attribute', 'attribute_machine_name')
    ->condition('field_value', field_value)
    ->execute();

Product

Create Product

Load Product

Load Product by "ID"

use Drupal\commerce_product\Entity\Product;

$product_id = 31;
$product = Product::load($product_id);

dump($product->getTitle()); // name of product
dump($product->get('plain_text222')->value); // text field
dump($product->get('body')->value); // body field

// this is used when you have only one variation for multiple variation use for loop
$variations = reset($product->getVariations());
if(isset($variations)){
  dump($variations->getSku());
}

Load Product by "loadByProperties"

  $productCollection = \Drupal::entityTypeManager()->getStorage('commerce_product')
    ->loadByProperties([
      'status' => 1,
      'title' => 'Sample Product for Testing'
  ]);

  $product = reset($productCollection);

  dump($product->getTitle()); // name of product
  dump($product->get('plain_text222')->value); // text field
  dump($product->get('body')->value); // body field

  // this is used when you have only one variation for multiple variation use for loop
  $variations = reset($product->getVariations());
  if(isset($variations)){
    dump($variations->getSku());
  }

List all Product & its Variations

  use Drupal\commerce_product\Entity\Product;

  ### Way 1
  $productCollection = \Drupal::entityTypeManager()->getStorage('commerce_product')->loadByProperties(['status' => 1]);
  $pids = array_keys($productCollection);
  $products = Product::loadMultiple($pids);
  foreach ($products as $product) {
    dump($product->getTitle());
    // this is used when you have only one variation for multiple variation use for loop
    $variations = reset($product->getVariations());
    if(isset($variations)){
      dump($variations->getSku());
    }
  }

  ### Way 2
  $pids = \Drupal::entityQuery('commerce_product')->condition('status', 1)->execute();
  $products = Product::loadMultiple($pids);
  foreach ($products as $product) {
    dump($product->getTitle());
    // this is used when you have only one variation for multiple variation use for loop
    $variations = reset($product->getVariations());
    if(isset($variations)){
      dump($variations->getSku());
    }
  }

Edit Product & its Variations

Edit Product by "ID"

use Drupal\commerce_product\Entity\Product;

$product_id = 31;
$product = Product::load($product_id);
$product->setTitle('Test Product Edited By John');
$product->save();
$variations = $product->getVariations();

foreach ($variations as $variation) {
   $variation->set('sku','Jonh-GDI');
   $variation->set('price', new Price('241.00', 'INR'));
   $variation->save();
}

Edit Product by "loadByProperties"

use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_price\Price;

### Way 1
$productCollection = \Drupal::entityTypeManager()->getStorage('commerce_product')->loadByProperties(['status' => 1]);
$pids = array_keys($productCollection);
$products = Product::loadMultiple($pids);
foreach ($products as $product) {
  $product->setTitle('Test Product Edited By John');
  $product->save();
  $variations = $product->getVariations();

  foreach ($variations as $variation) {
     $variation->set('sku','Jonh-GDI');
     $variation->set('price', new Price('241.00', 'INR'));
     $variation->save();
  }
}

Delete Product & its Variations

Delete Product by "ID"

use Drupal\commerce_product\Entity\Product;

$product_id = 31;
$product = Product::load($product_id);

// deleting product variation first
$variations = $product->getVariations();
foreach ($variations as $variation) {
   $variation->delete();
}

$product->delete();

Delete Product by "loadByProperties"

use Drupal\commerce_product\Entity\Product;

$productCollection = \Drupal::entityTypeManager()->getStorage('commerce_product')
    ->loadByProperties(['status' => 1]);

$pids = array_keys($productCollection);
$products = Product::loadMultiple($pids);
foreach ($products as $product) {
  $variations = $product->getVariations();
  foreach ($variations as $variation) {
     $variation->delete();
  }
  $product->delete();
}

Frontend: Product Variation

Load Product by "Variation ID"

  $variationId = 42;
  $variation_storage = \Drupal::service('entity_type.manager')->getStorage('commerce_product_variation');
  $product_variation = $variation_storage->load($variationId);
  $variation_id = $product_variation->id();

  // Get the product form the variation
  $product = $product_variation->getProduct();
  $product_id = $product_variation->getProductId();
  dump($product_id);

Load Variation Details by "ID"

$variationId = 42;
$product_variation = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')->load($variationId);
$price_number = $product_variation->get('price')->getValue()[0]['number'];
$price_currency = $product_variation->get('price')->getValue()[0]['currency_code'];

Load Variation by "loadByProperties"

$variationId = 42;
$product_variations = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')
  ->loadByProperties(['variation_id' => $variationId]);
$product_variation = reset($product_variations);
echo $price_number = $product_variation->get('price')->getValue()[0]['number'];
echo $price_currency = $product_variation->get('price')->getValue()[0]['currency_code'];

Update Variation by "ID"

$variationId = 42;
$product_variation = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')
  ->load($variationId);
$product_variation->set('price',new Price('261.00', 'INR'));
$product_variation->save();

echo $price_number = $product_variation->get('price')->getValue()[0]['number'];
echo $price_currency = $product_variation->get('price')->getValue()[0]['currency_code'];

Update Variation by "loadByProperties"

use Drupal\commerce_price\Price;

$variationId = 42;
$product_variations = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')
  ->loadByProperties(['variation_id' => $variationId]);
$product_variation = reset($product_variations);
$product_variation->set('price',new Price('251.00', 'INR'));
$product_variation->save();

echo $price_number = $product_variation->get('price')->getValue()[0]['number'];
echo $price_currency = $product_variation->get('price')->getValue()[0]['currency_code'];

Delete Variation by "ID"

$variationId = 42;
$product_variation = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')
->load($variationId);
$product_variation->delete();

Delete Variation by "loadByProperties"

$variationId = 42;
$product_variations = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')
  ->loadByProperties(['variation_id' => $variationId]);
$product_variation = reset($product_variations);
$product_variation->delete();

Search List of Product by SKU Pattern (Like Query)

Search List of Product by Name Pattern (Like Query)

List all variations of Product


Taxonomy

Load Taxonomy and Its Terms/vocabularies by "ID"

$termID = 1;
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($termID);
dump($term);

Load Taxonomy and Its Terms/vocabularies by "loadByProperties"

$term_name = 'Term Name';
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties(['name' => $term_name]);
dump($term);

Edit Taxonomy and Its Terms/vocabularies by "ID"

Edit Taxonomy and Its Terms/vocabularies by "loadByProperties"

Delete Taxonomy and Its Terms/vocabularies by "ID"

Delete Taxonomy and Its Terms/vocabularies by "loadByProperties"

Render Taxomony Terms/vocabularies in Tree Format

List Taxonomy and Terms/vocabularies inside Taxonomy

Create Taxonomy and Create Terms/vocabularies inside Taxonomy

Update Taxonomy and Update Terms/vocabularies inside Taxonomy

Delete Taxonomy and Delete Terms/vocabularies inside Taxonomy

Load Child Terms/vocabularies by Parent Term


DB Queries

Insert

$connection = \Drupal::database();
$values = [
  [
    'title' => 'Example',
    'uid' => 1,
    'created' => \Drupal::time()->getRequestTime(),
  ],
  [
    'title' => 'Example 2',
    'uid' => 1,
    'created' => \Drupal::time()->getRequestTime(),
  ],
  [
    'title' => 'Example 3',
    'uid' => 2,
    'created' => \Drupal::time()->getRequestTime(),
  ],
];
$query = $connection->insert('table_name')->fields(['title', 'uid', 'created']);
foreach ($values as $record) {
  $query->values($record);
}
$query->execute();

Select

$connection = \Drupal::database();

Update

$connection = \Drupal::database();

Delete

$connection = \Drupal::database();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment