You are here

public function Product::getDefaultVariation in Commerce Core 8.2

Gets the default variation.

Return value

\Drupal\commerce_product\Entity\ProductVariationInterface|null The default variation, or NULL if none found.

Overrides ProductInterface::getDefaultVariation

File

modules/product/src/Entity/Product.php, line 237

Class

Product
Defines the product entity class.

Namespace

Drupal\commerce_product\Entity

Code

public function getDefaultVariation() {
  if ($this->defaultVariation === NULL) {
    $default_variation = NULL;
    foreach ($this
      ->getVariations() as $variation) {

      // Return the first active variation.
      if ($variation
        ->isPublished() && $variation
        ->access('view')) {
        $default_variation = $variation;
        break;
      }
    }

    // Allow other modules to set the default variation.
    $event = new ProductDefaultVariationEvent($default_variation, $this);
    $event_dispatcher = \Drupal::service('event_dispatcher');
    $event_dispatcher
      ->dispatch(ProductEvents::PRODUCT_DEFAULT_VARIATION, $event);
    $this->defaultVariation = $event
      ->getDefaultVariation();
  }
  return $this->defaultVariation;
}