1

I have created a custom module to save product using API. I have created a model class and write a demo code and call this to my controller

class Company_Drop_Model_Product extends Mage_Core_Model_Abstract {

    public function addProducts() {
    $product = Mage::getModel('catalog/product');
    try {
        $product
            ->setStoreId(0) //you can set data in store scope
            ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
            ->setAttributeSetId(9) //ID of a attribute set named 'default'
            ->setTypeId('simple') //product type
            ->setCreatedAt(strtotime('now')) //product creation time
            //    ->setUpdatedAt(strtotime('now')) //product update time
            ->setSku('testsku61') //SKU
            ->setName('test product21') //product name
            ->setWeight(4.0000)
            ->setStatus(1) //product status (1 - enabled, 2 - disabled)
            ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
            ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
            ->setManufacturer(28) //manufacturer id
            ->setColor(24)
            ->setNewsFromDate('06/26/2014') //product set as new from
            ->setNewsToDate('06/30/2014') //product set as new to
            ->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
            ->setPrice(11.22) //price in form 11.22
            ->setCost(22.33) //price in form 11.22
            ->setSpecialPrice(00.44) //special price in form 11.22
            ->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
            ->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
            ->setMsrpEnabled(1) //enable MAP
            ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
            ->setMsrp(99.99) //Manufacturer's Suggested Retail Price
            ->setMetaTitle('test meta title 2')
            ->setMetaKeyword('test meta keyword 2')
            ->setMetaDescription('test meta description 2')
            ->setDescription('This is a long description')
            ->setShortDescription('This is a short description')
            ->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
            ->addImageToMediaGallery('media/catalog/product/1/0/10243-1.png', array('image', 'thumbnail', 'small_image'), false, false) //assigning image, thumb and small image to media gallery
            ->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' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 999 //qty
                )
            )
            ->setCategoryIds(array(2,3)); //assign product to categories
        $product->save();
        echo 'Product saved...';
        //endif;
    } catch (Exception $e) {
        Mage::log($e->getMessage());
    }
    }

    }

Controller File

class Company_Drop_IndexController extends Mage_Core_Controller_Front_Action {

    public function IndexAction() {
       Mage::getModel('drop/product')->addProducts();
    }
}

but it is not saving my product

I have debug the code generate the log files I am getting below error 2016-06-14T09:33:19+00:00 DEBUG (7): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (mdemo.catalog_product_entity, CONSTRAINT FK_CAT_PRD_ENTT_ATTR_SET_ID_EAV_ATTR_SET_ATTR_SET_ID FOREIGN KEY (attribute_set_id) REFERENCES eav_attribute_set (attribute_set_id) ON DELE), query was: INSERT INTO catalog_product_entity (entity_type_id, attribute_set_id, type_id, sku, created_at, updated_at) VALUES (?, ?, ?, ?, '2016-06-14 09:33:19', '2016-06-14 09:33:19')

  • did you look in the database and the product is not there, or you just don't see it in the admin panel? – Marius Jun 14 '16 at 6:44
  • I am not getting in the admin panel didn't check in the database. Yes check in the DB and there is no product – Jack Jun 14 '16 at 6:48
  • check in the database if there are new records appearing in catalog_product_entity when you run your code – Marius Jun 14 '16 at 6:49
  • I have checked the DB there is no product. Is there anything wrong with my code – Jack Jun 14 '16 at 6:50
  • are you sure your controller is being called? – Marius Jun 14 '16 at 6:56
1

You should try by setting up current store as Admin like below at the starting of addproducts() function.

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
  • Already Tried with this but not working. Thanks for your effort – Jack Jun 14 '16 at 7:03
  • It worked for me! ;-) – Giel Berkers Jun 16 '16 at 11:17
0

Try bellow code in file Mage::getModel('drop/product');

<?php
class Company_Drop_Model_Product extends Mage_Core_Model_Abstract
{
    public function addProducts()
    {
        $sku = "testsku61";
        $product = Mage::helper('catalog/product')->getProduct($sku, null, 'sku');
        try {
            $attributeSetId = Mage::getSingleton('eav/config')
                    ->getEntityType(Mage_Catalog_Model_Product::ENTITY)
                    ->getDefaultAttributeSetId();
            $product->setStoreId(0) //you can set data in store scope
            ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
            ->setAttributeSetId($attributeSetId) //ID of a attribute set named 'default'
            ->setTypeId('simple') //product type
            ->setCreatedAt(strtotime('now')) //product creation time
            ->setName('test product21') //product name
            ->setWeight(4.0000)
            ->setStatus(1) //product status (1 - enabled, 2 - disabled)
            ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
            ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
            ->setManufacturer(28) //manufacturer id
            ->setColor(24)
            ->setNewsFromDate('06/26/2014') //product set as new from
            ->setNewsToDate('06/30/2014') //product set as new to
            ->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
            ->setPrice(11.22) //price in form 11.22
            ->setCost(22.33) //price in form 11.22
            ->setSpecialPrice(00.44) //special price in form 11.22
            ->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
            ->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
            ->setMsrpEnabled(1) //enable MAP
            ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
            ->setMsrp(99.99) //Manufacturer's Suggested Retail Price
            ->setMetaTitle('test meta title 2')
            ->setMetaKeyword('test meta keyword 2')
            ->setMetaDescription('test meta description 2')
            ->setDescription('This is a long description')
            ->setShortDescription('This is a short description')
            ->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
            ->addImageToMediaGallery('media/catalog/product/1/0/10243-1.png', array('image', 'thumbnail', 'small_image'), false, false) //assigning image, thumb and small image to media gallery
            ->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' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 999 //qty
                )
            )
            ->setCategoryIds(array(2,3)); //assign product to categories
            if($product->getId()) {
                $product->setId($product->getId()); //SKU   
            }else {
                $product->setSku($sku); //SKU   
            }
            $product->save();
            echo 'Product saved...';
        //endif;
    } catch (Exception $e) {
            Mage::log($e->getMessage());
        }
    }
}
?>

Note: Above code first check sku in system if already created then updates product data otherwise create new product in system

  • Can you add an explanation of what your code is doing that is different from the question? It's not a very useful answer otherwise. – Robbie Averill Jun 14 '16 at 10:00
  • Also hint: he says in a comment that the attribute set was wrong – Robbie Averill Jun 14 '16 at 10:01
  • @Robbie : My code first check sku in system if already created then updates product data otherwise create new product in system – Abdul Jun 14 '16 at 10:12
  • I know what your code does but others may not, hence the suggestion to improve your answer :-) – Robbie Averill Jun 14 '16 at 10:14

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.