phpshopwareshopware6shopware6-app

How can I access the names of variant products in Shopware 6?


How can I get the name of a variant product via the product repository? So for example t-shirt L. Or only the option.

This is my code:

$cri2 = new Criteria();
$cri2->addFilter(new EqualsFilter('parentId', $itemProductId));
$cri2->addFilter(new EqualsFilter("active", 1));
$cri2->addFilter(new RangeFilter('stock', [ 'gt' => 0 ]));

I need the name of this option:

option image


Solution

  • The finished code is:

    $cri = new Criteria();
    $cri->addFilter(new EqualsFilter('parentId', "[YOUR PARENT ID]"));
    
    // Add options to associations
    $cri->addAssociations([
      'options'
    ]);
    
    // Loop through variant products
    foreach ($productRepository->search($cri, $context)->getElements() as &$variantRawItem) {
      
      // Map all options to array
      $options = array_map(function ($n) {
        return $n->get('translated')['name'];
      }, $variantRawItem->get('options')->getElements());
    
      // Create the options title
      $optionsTitle = implode(', ', $options);
    
      // $optionsTitle is now e.g.: L, Lila
    
    }