Search code examples
phpmysqlmagentoforeign-keysmagento-1.9

Adding custom magento options fails: Integrity constraint violation


I'm trying to create custom options from code, but when I try to give value to the 'values' array, I get this error (see the image).

So if I create an option with no fields in it ('values' empty array) everything works, but if I put an array with some elements it gives me error.

I can not understand why the integrity of the key is not guaranteed by the function 'addOption ()' or what I did wrong.

Below is also the piece of code:

// ... get function params etc ...

// conf
$product_id = 1686;
$store = 0;

// init
$product = Mage::getModel('catalog/product')->setStoreId($store)->load($product_id);
$options = Mage::getModel('catalog/product_option')->getProductOptionCollection($product);

// ... options clearing ...

// set option

$option = array(
            'title' => 'bundle',
            'type' => 'radio',
            'is_required' => 1,
            'sort_order' => 0,
            'values' => array(
                array(
                    'title' => 'Standard',
                    'price' => 10.11, 
                    'price_type' => 'fixed',
                    'sku' => 'ex_standard',
                    'sort_order' => 0,
                ),
                array(
                    'title' => 'Premium',
                    'price' => 20.50,
                    'price_type' => 'fixed',
                    'sku' => 'ex_premium',
                    'sort_order' => 0,
                ),
                array(
                    'title' => 'Deluxe',
                    'price' => 85.00,
                    'price_type' => 'fixed',
                    'sku' => 'ex_deluxe',
                    'sort_order' => 0,
                )
            )
        );

// apply changes

$product->setCanSaveCustomOptions(true);
$product->getOptionInstance()->addOption($option);
$product->setHasOptions(true);
$product->save();

Notes: Based on Magento 1.9, for custom option we use MageWorx implementation.

Error


Solution

  • I discovered a way to overcome the error: simply disable the control on foreign keys.

    Main Class function

    $write = Mage::getSingleton("core/resource")->getConnection("core_write");
    
    $this->setKeyCheck($write,0); // disable foreign keys
    
    /* ... Generate options ... */
    
    $this->setKeyCheck($write,1); // enable foreign keys
    

    Definition of the resolving function

    private function setKeyCheck($write,$status){
          $write->query("SET FOREIGN_KEY_CHECKS={$status}");
        }