1

I'm attempting to scan an incoming list of products and add any new ones to the catalog. Therefore, I must run a check on each product to see if it already exists.

I'm using a ProductRepositoryInterface via DI to load each product by SKU, but if the product doesn't exist within the catalog (new product), it fails with a \Magento\Framework\Exception\NoSuchEntityException.

How can I write logic around this so I can either: confirm the product exists, skip it gracefully, and move on OR confirm the product doesn't exist, and then add it? Is there something like an exists() method that I'm missing?

$product = $this->productRepository->get($xmlProductSku);
0

Same issue here Magento2 - ProductRepository always throws NoSuchEntityException

You'd use the concrete Exception class Magento are throwing in the try/catch block

0
Use this code you can skip the not exsist sku in magento 2 if you are updating anything in products
 <?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    ini_set('memory_limit', '-1');
    ini_set('max_execution_time', 0); 
    set_time_limit(0);
    error_reporting(E_ALL);
    
    $file = fopen('despUpdate.csv', 'r', '"'); // set path to the CSV file
    require __DIR__ . '/app/bootstrap.php';
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

    $objectManager = $bootstrap->getObjectManager();

    $state = $objectManager->get('Magento\Framework\App\State');
    $state->setAreaCode('adminhtml');
    $storeManager = $objectManager->get('\Magento\Store\Api\StoreRepositoryInterface');
    $currentStore = $storeManager->get('en');
    $websiteId = $currentStore->getWebsite()->getWebsiteId();
    print_r($currentStore->getData());
    // die();
    // used for updating product stock - and it's important that it's inside the while loop
    $stockRegistry = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface');
    

    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/stockupdate-new.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);

    $header = fgetcsv($file); // get data headers and skip 1st row

    $required_data_fields = 2;
$counter =0;
    while ( $row = fgetcsv($file, 40000, ",") ) {
        $data_count = count($row);
        if ($data_count < 1)
        {
            continue;
        }
        $data = array();
        $data = array_combine($header, $row);
        $sku = $data['sku'];
        // $desp = $data['description'];
        $getShortDescription = $data['short_description'];
        // $setStoreCode=$data['store_view_code'];
        // $setWebsite=$data['product_websites'];
        // $setStore=$data['store_id'];
        if ($data_count < $required_data_fields)
        {
            $logger->info("Skipping product sku " . $sku . ", not all required fields are present to create the product.");
            continue;
        }
        
        // $productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
        // $collection = $productCollectionFactory->create()->addAttributeToFilter('sku', $data['sku'])->setStore($currentStore)->load();
        // foreach ($collection as $product) 
        // {
                        
                try {
                    $product = $objectManager->create('Magento\Catalog\Model\ProductRepository')->get($sku);

                    $productSku=$product->getSku();

                    $product->setData('short_description', $getShortDescription);
                    // $product->setWebsiteIds($websiteId);
                    
                    //update the data the store wise

                    // $product->setData('store_view_code',$setStoreCode);
                    // $product->setData('website_id',$setWebsite);
                    // $product->setData('store_id',$setStore);

                    // for update the information on all store view
                    $product->setStoreId(0);
                    $product->save();
                    // print_r($product->getData());
                    
                    echo "Product Update-".$sku.PHP_EOL;
                } catch (Magento\Framework\Exception\NoSuchEntityException $e) {
                    
                    $logger->info('Error importing product sku: '.$sku.'. '.$e->getMessage());
                     // $product = false;
                    continue;
                }     
}
fclose($file);

?>
-2

What's the problem to catch exception...

try {
    $product = $this->productRepository->get($xmlProductSku);
} catch (\Exception $e) {
    $product = false;
}

if ($product) {
   //some logic
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.