Magento 1.9 – Set Custom Options Programmatically in Loop

custom-optionsmagento-1.9

I am about to import a product via script and like to set several custom options for this product.

I build an array with the specific data:

$option = array(
    'option1' => array(
        'title' => 'title',
        'type' => 'drop_down',
        'is_require' => 0,
        'sort_order' => 1,
        'values' => getOptions('option1')
    ),
    'option2' => array(
        'title' => 'title',
        'type' => 'checkbox',
        'is_require' => 0,
        'sort_order' => 2,
        'values' => getOptions('option2')
    ) ...

Now I try to set the custom options in a loop:

foreach ($option as $key => $val) {
    $product->setProductOptions(array($option[$key]));
    $product->setCanSaveCustomOptions(true);
}

But this only saved the last option in the loop, so the other ones will be overwritten.

Could you help me out what I am missing?

Best Answer

Some testing led me to the solution.

I rearranged my option array to:

$option = array(
    array(
        'title' => 'option1',
        'type' => 'drop_down',
        'is_require' => 0,
        'sort_order' => 1,
        'values' => getOptions('option1')
    ),
    array(
        'title' => 'option2',
        'type' => 'checkbox',
        'is_require' => 0,
        'sort_order' => 2,
        'values' => getOptions('option2')
    ), ...

And without the loop i simply save the multiple options:

$product->setProductOptions($option);
$product->setCanSaveCustomOptions(true);
$product->save();
Related Topic