Skip to content


Adding “Mutliselect” Attributes in Magento

In my current work, I’ve come across the need to create “multiselect” attributes in Magento. These are handy for selecting media formats (i.e. vhs, dvd, blue-ray) or product colors (red, green, blue, etc). The following code creates a mutliselect attribute named Media Format with labels of “Media Format” on the front and back ends with values of dvd, vhs, blue-ray.
The array indices of 0 and 1 refer to the Admin or Default Store View (i.e. front end). This is based on code from the AdminHtml/controllers/Catalog/Product/AttributeController.php script in Magento v. 1.3.2.2.

#!/usr/bin/php
<?php
define('MAGENTO', realpath('/var/www/magento'));
ini_set('memory_limit', '128M');
 
require_once MAGENTO . '/app/Mage.php';
 
Mage::app();
 
$model = Mage::getModel('catalog/entity_attribute');
 
$model->setAttributeCode('mediaFormat');//attribute code
$model->setIsComparable(0);
$model->setIsConfigurable(0);	
$model->setIsFilterable(0);
$model->setIsFilterableInSearch(0);	
$model->setIsGlobal(0);
$model->setIsRequired(0);
$model->setIsSearchable(0);	
$model->setIsUnique(0);	
$model->setIsUsedForPriceRules(0);	
$model->setIsVisibleInAdvancedSearch(0);	
$model->setIsVisibleOnFront(0);	
$model->setDefaultValueYesno(0);
$model->setUsedInProductListing(0);	
 
$model->setFrontendInput('multiselect'); //make it a multiselect/dropdown
//0 is the admin value, 1 is the "default store view" (frontend) value
$frontEndLabel=array('0'=>'Media Format',
                      '1'=>'Media Format');
 
$model->setFrontendLabel($frontEndLabel);	
//0 is the admin value, 1 is the "default store view" (frontend) value
$optionData = array('value' =>
						array('option_0'=>array('0'=>'dvd','1'=>'dvd'),
						      'option_1'=>array('0'=>'vhs','1'=>'vhs'),     
						      'option_2'=>array('0'=>'blue-ray','1'=>'blue-ray')     
						)
					,
			        'order' =>
						array('option_0'=>1,
							  'option_1'=>2,
							  'option_2'=>3)
			   );
$model->setOption($optionData);
 
 
$data['backend_model'] = 'eav/entity_attribute_backend_array';
$data['apply_to'] = array();
$model->addData($data);
$model->setEntityTypeId(Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId());
$model->setIsUserDefined(1);
var_dump($model);
 
try {
	$model->save();
}
catch(Exception $e) {
    echo $e->getMessage();
}
?>

Posted in magento, php.

Tagged with , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.

Spam Protection by WP-SpamFree