Skip to content

Instantly share code, notes, and snippets.

@bastianccm
Created April 17, 2013 13:32
Show Gist options
  • Save bastianccm/5404315 to your computer and use it in GitHub Desktop.
Save bastianccm/5404315 to your computer and use it in GitHub Desktop.
<?php
// [...]
/**
* pregenerate missing attribute options
*
* @param array $products
*/
public function pregenerateAttributeOptions($products)
{
$attributes = array();
$config = $this->getConfig()->config;
foreach (array_merge((array)$config->attributes, (array)$config->attributes_new) as $productAttr => $attr) {
$attributeInfo = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attr);
if (in_array($attributeInfo->getFrontendInput(), array('select', 'multiselect'))) {
$attributes[$attr] = $productAttr;
}
}
$optionscache = array();
foreach($attributes as $attr => $productAttr) {
$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attr);
$sourceModel = $attribute->getSource();
$sourceModel->setAttribute($attribute);
foreach($sourceModel->getAllOptions() as $option) {
$optionscache[$attr][strtolower(trim($option['label']))] = 1;
}
}
foreach ($products as $product) {
foreach($attributes as $attr => $productAttr) {
$labels = $product->getData($productAttr);
if (!is_array($labels)) {
$labels = array($labels);
}
foreach ($labels as $label) {
$label = strtolower(trim($label));
if(!isset($optionscache[$attr][$label])) {
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$option = array(
'attribute_id' => $installer->getAttributeId(Mage::getModel('catalog/product')->getResource()->getTypeId(), $attr),
'value' => array(
'x' => array($label),
),
);
$installer->addAttributeOption($option);
$installer->endSetup();
$optionscache[$attr][$label] = 1;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment