Magento – Set Dropdown Attribute Value of a Product, Add Option if not Present

A quick little function for PHP scripts. Dropdown attributes have a limited set of allowed values. Say you have products that you wish the customer to be able to filter by Manufacturer on the front-end: the manufacturer attribute must be a drop-down in order for it to be filterable. If your products are added from an importer script, the script needs to be able to add a missing Manufacturer to the options of the attribute, if it is not already on the list. This function handles that transparently. If the value exists, it is set. If it does not exist, it is created and then set.

function setOrAddOptionAttribute($product, $arg_attribute, $arg_value) {
	$attribute_model = Mage::getModel('eav/entity_attribute');
	$attribute_options_model = Mage::getModel('eav/entity_attribute_source_table');

	$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
	$attribute = $attribute_model->load($attribute_code);

	$attribute_options_model->setAttribute($attribute);
	$options = $attribute_options_model->getAllOptions(false);

	// determine if this option exists
	$value_exists = false;
	foreach($options as $option) {
		if ($option['label'] == $arg_value) {
			$value_exists = true;
			break;
		}
	}

	// if this option does not exist, add it.
	if (!$value_exists) {
		$attribute->setData('option', array(
			'value' => array(
				'option' => array($arg_value,$arg_value)
			)
		));
		$attribute->save();
	}

	$product->setData($arg_attribute, $arg_value);
}

An example:

setOrAddOptionAttribute($product, 'manufacturer', 'Samsung');
Tagged as: ,