Magento: custom options with store-specific title

While working on a Magento project, I was trying to do something that seemed trivial at first, but sadly I found absolutely no documentation about it over the Internet.

First part of the problem was documented: I needed to create custom options on a product, and I’ve been able to find a couple of examples. Second part was tricky: I needed to specify a different title for each store the product was related to. For this part, I found almost nothing useful.

I spent some time reading Magento’s API documentation (here I’m talking about PHP API, not the SOAP or XMLRPC API), trying things, var_dumping and print_r-ing objects, and so on. After a couple hours of head scratching, I finally got it working.

In fact, the solution is pretty simple. First, you need to have the ID of the product that will own the option. Either you load an existing product, or you create a new one and then save it (so its ID is generated); that’s the $product variable. Then let’s just create the option object, initialize its properties, bind it to its product and save it:

$option = Mage::getModel('catalog/product_option');
$opt->setTitle('Color');
$opt->setType('field');
$opt->setPriceType('fixed');
$opt->setPrice(0);
$opt->setProductId($product->getId());
$opt->save();

Now you have a new text field option, with its default title being Color. Now let’s say you have a French store and you need to assign the title Couleur for that store. You simply need to change the option’s current store ID, set the French title and save:

$opt->setStoreId(Mage::app()->getStore('french')->getId());
$opt->setTitle('Couleur');
$opt->save();

(here I loaded the store ID using the store’s code property)

Same thing applies for values when using multi-valued options. Here I’ve got a drop_down option offering various sizes, and I need to add a new size named Very Small. Similar as before, you need to have an existing product and option ($product and $option variables):

$value = Mage::getModel('catalog/product_option_value');
$value->setTitle('Very Small');
$value->setPriceType('fixed');
$value->setPrice(0);
$value->setProductId($product->getId());
$value->setOptionId($option->getId());
$value->save();

Then, let’s change the value’s store ID, set the French title Très Petit and save:

$value->setStoreId(Mage::app()->getStore('french')->getId());
$value->setTitle(utf8_encode('Très Petit'));
$value->save();

In case you were wondering: the utf8_encode allows Magento to correctly digest accented characters.

This entry was posted in Magento, PHP. Bookmark the permalink.

One Response to Magento: custom options with store-specific title

Leave a Reply

Your email address will not be published. Required fields are marked *