سؤال

How can I convert a product attribute type from Text to Select in the Magento Backend. Is there any in-built functionality or we need to write custom code for that?

I already have attribute values assigned for many products, so don't want to lose that in this conversion.

Thanks

هل كانت مفيدة؟

المحلول

You would first need to have a script that stores all values per product in a CSV for example

[...]
$collection = Mage::getModel('catalog/product')
                        ->getCollection()
                        ->addAttributeToSelect('sku')
                        ->addAttributeToSelect('your-attribute');

foreach ($collection as $product) {
    echo "{$product->getId()};{$product->getData('your-attribute')}\n";
}
[...]

executing this from the commandline php /path/to/script.php > values.csv will create a CSV with the ID's and attribute values.

Now the next step would be to remove the old attribute and create a new one with the text values as dropdown options.

Then we need to import those values again retrieving the option ID from the value which should now be the admin label

[...]

$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'your-attribute'); 

$attribute_source = Mage::getModel('eav/entity_attribute_source_abstract');
$attribute_source->setAttribute($attribute);

if (($handle = fopen("your-csv-file.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
        list($_id, $_value) = $data;

        $product = Mage::getModel('catalog/product')->load($_id);
        $product->setData('your-attribute', $attribute_source->getOptionId($_value));

        try {
            $product->save();
        } catch(Exception $e) {
            echo "{$_id}: {$e}";
        }
    }
    fclose($handle);
}

[...]

This code is untested so please don't use it in a production environment. Let me know if it worked for you.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى magento.stackexchange
scroll top