drupal-8drupal-commerce

How to load all variations and its id by using product_id programmatically using Drupal Commerce-2.x?


How to load the variations_id from product_id on form alter in Drupal commerce-2.x?


Solution

  • You need first to load Product variation entity, You need to get Product variation ids from loaded product and then extract SKU, Price, Currency Code and etc.

    $parameter = \Drupal::routeMatch()->getParameter('commerce_product');
    $product = \Drupal\commerce_product\Entity\Product::load((int)$parameter->id());
    
    /*Load Product Variations*/
    $entity_manager = \Drupal::entityManager();
    $product_variation = $entity_manager->getStorage('commerce_product_variation')->load((int)$product->getVariationIds()[0]);
    $price_number = $product_variation->get('price')->getValue()[0]['number'];
    $price_currency = $product_variation->get('price')->getValue()[0]['currency_code'];