0

i am trying to add product from frontend programatically following this link :

Magento: Adding new products programmatically

but i want to extend it to add custom options too to it .And i added the following code to it

$options = array();
        $options[$sku] = array(
        'title' => 'Option Title',
        'type' => 'radio',
        'is_require' => 1,
        'sort_order' => 0,
        'values' => array()
        );
        $options[$addvp['product']['sku']]['values'][] = array(
        'title' => 'Option Value 1',
        'price' => 0.00,
        'price_type' => 'fixed',
        'sku' => '',
        'sort_order' => '1'
        );
        $options[$sku]['values'][] = array(
        'title' => 'Option Value 2',
        'price' => 89.00,
        'price_type' => 'fixed',
        'sku' => '',
        'sort_order' => '1'
        );

    foreach($options as $sku => $option) {
        $id = Mage::getModel('catalog/product')->getIdBySku($sku);
        $product = Mage::getModel('catalog/product')->load($id);

        if(!$product->getOptionsReadonly()) {
        $product->setProductOptions(array($option));
        $product->setCanSaveCustomOptions(true);
        //$product->save();
        }
    }

but it prints this error instead of adding custom option to product.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`vendor`.`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 DEL)
Community
  • 1
  • 1
atif
  • 1,693
  • 13
  • 38
  • 70

2 Answers2

1

http://www.fontis.com.au/blog/magento/add-product-custom-options

Note:

The above link did what i want it to do. But one thing to be kept in mind that you must add the custom option to a product already exists/saved.

atif
  • 1,693
  • 13
  • 38
  • 70
0

I had a similar issue. Turned out that the auto-generated SKU was somehow invalid or not properly saved on the new product I created for testing. The product was not invalid, as it did save properly on the first go, but when I revisited the product via the CMS and tried to click "save and continue" it suddenly prompted me to enter a SKU. When I re-entered the auto-generated sku it worked!

So the short answer would be: Check that your product exists by that SKU number. If it does, re-check that the SKU is being saved properly.

Seph Soliman
  • 300
  • 2
  • 6