Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if a category exists Shopware 6

Check if a category existsyour text

I have such code

 $categoryService = $this->container->get('category.repository');
    $newCategory = [
            'name' => 'Profi-Shop',
            'parentId' => null,
            'customFields' => [
        ],
    ];

    $categoryService->create([$newCategory], $context->getContext());

It is executed every time. How to execute it only if there is no such category

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to check if your category exists prior creating it. If it does, then just skip creation step:

use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;

$categoryService = $this->container->get('category.repository');
$newCategoryName = 'Profi-Shop';

// Search for the category first
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('name', $newCategoryName));
$existingCategory = $categoryService->search($criteria, $context->getContext());

// Create it if there's no match found:
if ($existingCategory->getTotal() === 0) {
    $newCategory = [
        'name' => $newCategoryName,
        'parentId' => null,
        'customFields' => [],
    ];

    $categoryService->create([$newCategory], $context->getContext());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading