Skip to content

Instantly share code, notes, and snippets.

@obukhow
Last active January 29, 2016 11:15
Show Gist options
  • Save obukhow/9251960 to your computer and use it in GitHub Desktop.
Save obukhow/9251960 to your computer and use it in GitHub Desktop.
Magento update text attribute type to select
<?php
require "app/Mage.php";
umask(0);
Mage::init('admin', 'store');
$attrCode = 'model'; //your attribute code here
$attrId = (int) Mage::getModel('eav/entity_attribute')->getIdByCode(Mage_Catalog_Model_Product::ENTITY, $attrCode);
$resource = Mage::getSingleton('core/resource')->getConnection('core_write');
try {
$resource->beginTransaction();
/**
* Collect old products values
*/
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('sku')
->addAttributeToSelect($attrCode)
->addAttributeToFilter($attrCode, ['notnull' => true]);
$data = $collection->getData();
$productData = [];
foreach ($data as $product) {
$productData[$product['entity_id']] = $product[$attrCode];
}
$select = "select distinct value from `catalog_product_entity_varchar` where `attribute_id` = {$attrId};";
$modelValues = $resource->fetchCol($select);
/**
* Change attribute type
*/
$updateAttrType = "UPDATE `eav_attribute` SET `backend_type` = 'int', `frontend_input` = 'select', `source_model`='eav/entity_attribute_source_table' WHERE `attribute_id` ={$attrId};";
$resource->query($updateAttrType);
$deleteOldValues = "delete from `catalog_product_entity_varchar` where `attribute_id` = {$attrId}";
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
/**
* Add options to the attribute
*/
$iProductEntityTypeId = Mage::getModel('catalog/product')->getResource()->getTypeId();
$aOption = array();
$aOption['attribute_id'] = $attrId;
for ($iCount = 0; $iCount < sizeof($modelValues); $iCount++) {
if (!isset($modelValues[$iCount])) {
continue;
}
$aOption['value']['option' . $iCount][0] = $modelValues[$iCount];
}
$installer->addAttributeOption($aOption);
$installer->endSetup();
/**
* Update products with new data
*/
$attribute = Mage::getModel('eav/config')->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attrCode);
$allOptions = $attribute->getSource()->getAllOptions(true, true);
foreach ($allOptions as $instance) {
$myArray[$instance['label']] = $instance['value'];
}
foreach ($productData as $productId => $value) {
if (!isset($myArray[$value])) {
continue;
}
Mage::getModel('catalog/product_action')->updateAttributes([$productId], [$attrCode => $myArray[$value]], 0);
}
$resource->commit();
} catch (Exception $e) {
echo $e->getMessage();
Mage::logException($e);
$resource->rollBack();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment