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

1.1k Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

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

}
1
On

When you want to search for a specific name you can use

$cri2->addFilter(new EqualsFilter('name', 't-shirt L'));

When you want to search for the option name instead you can use

$cri2->addFilter(new EqualsFilter('options.option.name', 't-shirt L'));

When you don't want to search by name, but only what to get the name of a given product:

$product = $this->productRepository->search($cri2, $context)->getFirst();

echo $product->getName();
2
On

I believe the confusion is here:

enter image description here

Just note that this is not the name of the variant, it's just it's options concatenated as preview.

You can see inn the picture below that the actual name is null & therefore inherits the parents' name: enter image description here

If you change the name from the variant product, then it will not be null anymore. enter image description here

To create an actual name you will have to manually pull its options using associations. Here is an example of a query you might be looking for. After you get the data, just create the name yourself out of the variation data. High chance that this is how Shopware6 does it in the picture provided.


$criteria = (new Criteria()
            // loads non-child products
            ->addFilter(new EqualsFilter('product.parentId', null))
            ->addAssociations([
                'options',
                'variation',

                'children',
                'children.options',
                'children.properties',
                'children.properties.group'
            ])