As you know magento table structure is been built upon EAV (Entity Attribute Value) structure. Magento uses EAV to add more number of fields to table dynamically. Just to get one single record, Magento joins 4-5 tables to get data in EAV. So juts to convert one filed type to another you have to edit more number of tables as well and take their value as well which is not a good idea and can’t be managed easily. So lets what EAV is an how it works.
Lets take a little look about EAV so that you will understand better and can understand how to convert attribute type.

EAV(Entity Attribute Value ):
EAV is a technique which allows you to add unlimited columns to your table dynamically. I mean the fields which is represented in ‘column’ way in a regular table, is represented in a ‘row’ (records) way in EAV table.
Entity:
Entity represent magento data item such as product, categories, customer, orders.Each entity will have its own record in database.
Attribute:
Attribute represent magento data item which belongs to entity. for example product entity has attribute such as price, name, status etc.
Value:
Value is just the value of an attribute that linked to.
So in the table table structure way one table hold attribute values called eav_attribute and 5-6 tables which holds entity and data in fully normalized form which will be different for different datatype like
- For integer value : eav_entity_int
- For Varchar value : eav_entity_varchar
- For Datetime values : eav_entity_datetime
- For Decimal/float values : eav_entity_decimal
- For holding text (mysql Text type) values : eav_entity_text.
So let come back to our conversion for convert attribute type in magento
Here I have a custom script called “AttributeTypeConversion” and will work for text type to price and vice versa.In this script you can also convert more number attribute in a single time.No need to go for database table and to change manually . You will only also need to enter the attribute type and attribute code then submit and finally you will be getting the number records which was changed and make sure you will do this in development server not production server and also take whole database backup to avoid damage of database table.
Just download the AttributeTypeConversion.php file from AttributeTypeConversion or from last of article and place that php file in magento root directory and run in browser by www.yourdomain.com/AttributeTypeConversion.php
Here is the article to know How to import export sql file from command line.
1 |
mysqldump -u [uname] -p[pass] dbname > db_backup.sql |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
< ?php define('MAGENTO', realpath(dirname(__FILE__))); require_once MAGENTO . '/app/Mage.php'; Mage::app(); $manageAttribute = new manageAttribute(); class manageAttribute{ private $_attributeCodesArray; private $_attributeCodes; private $_success = false; private $_frontendInput; private $_backendType; private $_message; private $_from; private $_to; /* * Initialize the Mage application */ function __construct() { // Increase maximum execution time to 4 hours ini_set('max_execution_time', 14400); // Set working directory to magento root folder chdir(MAGENTO); // Make files written by the profile world-writable/readable Mage::setIsDeveloperMode(true); ini_set('display_errors', 1); umask(0); Mage::app('admin'); Mage::register('isSecureArea', 1); // Run the main application $this->_runMain(); } /* * Run the main application and call the appropriate function * depending on the command. */ private function _runMain() { $this->_redirectUrl = $_SERVER['PHP_SELF']; if ($_SERVER["REQUEST_METHOD"] == "POST") { if(!$this->validate()){ $messageType = 'error'; $this->DisplayForm($messageType); return false; } $this->changeInEavAttributeTable($this->_backendType,$this->_frontendInput); //return false; $this->changeAttributeType($this->_from,$this->_to); } $messageType = 'success'; $this->DisplayForm($messageType); } function validate(){ if((isset($_POST['attribute_codes']) && $_POST['attribute_codes'] != '')){ $this->_attributeCodes = $_POST['attribute_codes']; $this->_attributeCodesArray = explode(',',(string)$this->_attributeCodes); }else{ $this->_message = 'Please enter attribute code separated by comma'; return false; } if((isset($_POST['frontend_input']) && $_POST['frontend_input'] != '')){ $this->_frontendInput = $_POST['frontend_input']; }else{ $this->_message = 'Please enter attribute type'; return false; } if($this->_frontendInput == 'price'){ $this->_from = 'catalog_product_entity_varchar'; $this->_to = 'catalog_product_entity_decimal'; $this->_backendType = 'decimal'; }else if($this->_frontendInput == 'text'){ $this->_from = 'catalog_product_entity_decimal'; $this->_to = 'catalog_product_entity_varchar'; $this->_backendType = 'varchar'; } return true; } function changeInEavAttributeTable($backendType,$frontendInput){ $array = $this->_attributeCodesArray; $connection = $this->_getConnection('core_write'); foreach($this->_attributeCodesArray as $code){ $sql = 'UPDATE '.$this->_getTableName('eav_attribute').' SET frontend_input = '.'"'.$frontendInput.'"'.', backend_type = '.'"'.$backendType.'"'.' WHERE attribute_code = '.'"'.$code.'"'; $connection->query($sql); } $attributeIds = (string) implode(',', $this->_getAttributeIds()); $this->_updatedMessage = 'eav_attribute table is UPDATED with attribute codes '.$this->_attributeCodes.' and attribute Ids '.$attributeIds; } function changeAttributeType($from,$to){ # EDIT HERE...Note the single quotes inside the double quotes. This is necessary unless you modify the function yourself # Note that these attribute codes are those attributes whose type is to be changed. //$this->_attributeCodesArray = array("'purchase_price'"); $connection = $this->_getConnection('core_write'); $attributeIds = (string) implode(',', $this->_getAttributeIds()); $entityTypeId = (int) $this->_getEntityTypeId(); $sql = 'SELECT * FROM ' . $this->_getTableName($this->_from) . ' WHERE attribute_id IN ('.$attributeIds.') AND entity_type_id = '.$entityTypeId; $rows = $connection->fetchAll($sql); $insertCount = 1; $deleteCount = 1; $insertOutput = ''; $deleteOutput = ''; foreach($rows as $row){ $checkIfDecimalValueExists = $this->_checkIfDecimalValueExists($row); if(!$checkIfDecimalValueExists){ $sql = 'INSERT INTO ' . $this->_getTableName($this->_to) . ' (`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (?,?,?,?,?)'; $price = $row['value']; $price = trim(str_replace(',', '.', $price)); $connection->query($sql, array($row['entity_type_id'], $row['attribute_id'], $row['store_id'], $row['entity_id'], $price)); $insertOutput .= $insertCount . '> INSERTED::' . $connection->lastInsertId() . ' :: ' .$row['value'] . ' => ' . $price . '<br />'; $insertCount++; } $sql = 'DELETE FROM ' . $this->_getTableName($this->_from) . ' WHERE value_id = ?'; $connection->query($sql, $row['value_id']); $deleteOutput .= $deleteCount . '> DELETED::'.$row['value_id'].'<br />'; $deleteCount++; } $this->_message .= '==========UPDATED===============================<br />'; $this->_message .= '<strong>'.$this->_updatedMessage.'</strong><br />'; $this->_message .= '==================================================<br />'; $this->_message .= '==========INSERTED=======================================<br />'; $this->_message .= '<strong>INSERTED from table '.$this->_from.' to table '.$this->_to.'</strong><br />'; $this->_message .= $insertOutput; $this->_message .= '=================================================<br />'; $this->_message .= '==========DELETED=======================================<br />'; $this->_message .= '<strong>DELETED from '.$this->_from.'</strong><br />'; $this->_message .= $deleteOutput; $this->_message .= '=================================================<br />'; } function _getTableName($tableName){ return Mage::getSingleton('core/resource')->getTableName($tableName); } function _getConnection($type = 'core_read'){ return Mage::getSingleton('core/resource')->getConnection($type); } function _getAttributeIds(){ //global $_attributeCodes; $attributeCodes = ''; foreach($this->_attributeCodesArray as $codes){ $attributeCodes .= "'".$codes."',"; } $attributeCodes = rtrim($attributeCodes, ","); //$attributeCodes = (string) implode(',', $this->_attributeCodesArray); $connection = $this->_getConnection('core_read'); $sql = "SELECT attribute_id FROM " . $this->_getTableName('eav_attribute') . " WHERE attribute_code IN ( ". $attributeCodes . " )"; //SELECT attribute_id FROM eav_attribute WHERE attribute_code IN('custom_price_new','purchase_price'); return $connection->fetchCol($sql); } function _getEntityTypeId(){ $connection = $this->_getConnection('core_read'); $sql = "SELECT entity_type_id FROM " . $this->_getTableName('eav_entity_type') . " WHERE entity_type_code = 'catalog_product'"; return $connection->fetchOne($sql); } function _checkIfDecimalValueExists($row){ $connection = $this->_getConnection('core_write'); $sql = 'SELECT COUNT(*) FROM ' . $this->_getTableName($this->_to) . ' WHERE attribute_id = ? AND entity_type_id = ? AND store_id = ? AND entity_id = ?'; $result = $connection->fetchOne($sql, array($row['attribute_id'], $row['entity_type_id'], $row['store_id'], $row['entity_id'])); return $result > 0 ? true : false; } private function DisplayForm($messageType,$logMessage='') { // Set character set to UTF-8 header("Content-Type: text/html; charset=UTF-8"); ?> < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> <title>Change attribute type from price type to text type and vice versa</title> <style type="text/css"> .main_div{margin:0 auto;width: 60%;} .input_type{width: 98%;} .main_table{margin: 1em auto;width: 100%;} .second{width: 70%;} .first{width: 30%;text-align: right} </style> </head> <body> <form method="post" action=""> <h2 style="text-align:center;">Welcome to change atribute type</h2> <div style="clear:both;"></div> <div class="main_div"> <fieldset> <legend>Change attribute type from price type to text type and vice versa</legend> < ?php if($_SERVER["REQUEST_METHOD"] == "POST"): ?> <table style="margin: 1em auto;" cellpadding="2"> <tr> <td> < ?php if($logMessage){ print_r($logMessage); } ?> </td> < ?php if($messageType == 'success'): ?> <td style="color: #48961B;">< ?php echo $this->_message; ?></td> < ?php elseif($messageType == 'error'): ?> <td style="color: #F70E0E;">< ?php echo $this->_message; ?></td> < ?php endif ?> </tr> </table> < ?php endif; ?> <table class="main_table" cellpadding="2"> <tr> <th class="first" style="">Enter attribute codes separated by comma: </th> <th class="second"><input class='input_type' type="text" name='attribute_codes' value=""/></th> </tr> <tr> <th class="first">Enter attribute type to convert: </th> <th class="second"><input class='input_type' type="text" name='frontend_input' value=""/></th> </tr> <tr> <th class="first"></th> <th class="second"><input type="submit" name="submit" value="Submit"/></th> </tr> </table> </fieldset> </div> </form> </body> </html> < ?php } } |
Download magento convert attribute type file from AttributeTypeConversion
Thanks for visiting the article magento convert attribute type.
Thanks Jyoti this artical is very helpfull for me.
thanks once again