2

I have a requirement where I have to update Magento products from outside of Magento code (a CodeIgniter project).

Everything is working perfectly, but, one thing is wrong, if I save 2 products with same SKU, my code does not throw exception.

While if I go to my Magento website's admin section and try to set a duplicate SKU for any product, it does show error that SKU cannot be duplicated.

But why the following code is allowing me to set duplicate SKU? I am posting only relevant code here.

   try {
        $url = preg_replace('#[^0-9a-z]+#i', '-', $product_name);
        $url = strtolower($url);

        $simpleProduct
                ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
                ->setAttributeSetId(20) //ID of a attribute set named 'default'
                ->setTypeId('simple') //product type
                ->setCreatedAt(strtotime('now')) //product creation time
                ->setSku($_POST['sku']) //SKU
                ->setName($_POST['product_name']) //product name
                ->setUrlKey($_POST['url_key'])
                ->setBrand($_POST['brand'])->setType($_POST['type'])
                ->setStatus($_POST['status'] == 1 ? 1 : 2) //product status (1 - enabled, 2 - disabled)
                ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
                ->setNewsFromDate(strtotime('now')) //product set as new from
                ->setNewsToDate(strtotime('+1 week')) //product set as new to
                ->setPrice($_POST['price']) //price in form 11.22
                ->setCost($_POST['price']) //price in form 11.22
                ->setSpecialPrice($_POST['discount_price'])

                ->setMetaTitle($_POST['meta_title'])
                ->setMetaKeyword($_POST['meta_keyword'])
                ->setMetaDescription($_POST['meta_description'])
                ->setDescription($_POST['description'])
                ->setShortDescription($_POST['short_description'])
                ->setStockData(array(
                    'use_config_manage_stock' => 0, //'Use config settings' checkbox
                    'manage_stock' => 1, //manage stock
                    'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
                    'max_sale_qty' => $_POST['quantity'], //Maximum Qty Allowed in Shopping Cart
                    'is_in_stock' => $_POST['quantity'] == 0 ? 0 : 1, //Stock Availability
                    'qty' => $_POST['quantity'] //qty
                        )
                )
                ->setCategoryIds(unserialize($_POST['product_groups_category_map'])); //assign product to categories

        Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

        $simpleProduct->save($simpleProduct);

        if (!empty($_POST['product_groups_images'])) {
            if ($_POST['id_in_magento'] != 0) {
                $mediaApi = Mage::getModel("catalog/product_attribute_media_api");
                $mediaApiItems = $mediaApi->items($simpleProduct->getId());

                foreach ($mediaApiItems as $item) {
                    $datatemp = $mediaApi->remove($simpleProduct->getId(), $item['file']);
                }
            }

            $simpleProduct->load($_POST['id_in_magento']);
            $simpleProduct->setMetaTitle($_POST['meta_title']);

            foreach (unserialize($_POST['product_groups_images']) as $img) {
                $simpleProduct->addImageToMediaGallery($img, array('image', 'small_image', 'thumbnail'), false, false);
            }
        }
        Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

        $simpleProduct->save($simpleProduct);

        $return['magento_id'] = $simpleProduct->getId();
        $return['url_key'] = $simpleProduct->getUrlKey();
    } catch (Exception $e) {
        Mage::log($e->getMessage());
        $return['error'] = $e->getMessage();
    }

What is wrong with code?

PS:

I repeat that if I try to set duplicate SKU from backend of Magento website, it shows a normal error that SKU cannot be duplicate.

1
  • you want validation for sku or you want to know why you wont get execption ? Commented Oct 27, 2016 at 12:17

1 Answer 1

-1

That's because you don't valide your product before saving it.

To do so, you need to call:

$product->validate();

Before saving your product.

On top of that the save() method does not accept any argument it should be:

$simpleProduct->save();
3
  • it returns nothing :( I did ` echo '<pre>'; var_dump($simpleProduct->validate()); exit; $simpleProduct->save($simpleProduct);` and its empty
    – Umair Ayub
    Commented Oct 27, 2016 at 13:20
  • @Umair the save() method does not accept any argument, it should be $simpleProduct->save(); Commented Oct 27, 2016 at 13:20
  • ok good to know, but $product->validate() returns nothing ... empty results.
    – Umair Ayub
    Commented Oct 27, 2016 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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