Magento – Set Product Dropdown and Multiselect Values Programmatically

Here’s how to programmatically, meaning through code, set a product’s attribute value when the attribute is of type Dropdown or Multiselect.  For dropdown, we’ll be interested in setting only a single value.  And obviously for multiselect, we’ll be interested in setting multiple values.

With Text attributes such as Name and Description, you can do something like:

$product->setName( 'My Sweet Shirt' );
$product->setDescription( 'This shirt will make you look good, thus impressing girls.' );

Unfortunately, this won’t work for attributes whose values are predefined.  Instead of cursing Magento, think of it as a data-integrity/validation measure.

Anyway, assuming you already have a $product object, our overall process will be to:

  1. Load an attribute object for the attribute you want to work on
  2. Load the collection of that attribute’s values
  3. Make your choices (different for Dropdown and Multiselect)
  4. Save the product

1. Load an attribute object for the attribute you want to work on

$attribute = Mage::getModel('eav/entity_attribute');
$attribute->loadByCode( 4, 'color' );

2. Load the collection of that attribute’s values

$values = array();
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
	->setAttributeFilter( $attribute->getId() )
	->setStoreFilter( Mage_Core_Model_App::ADMIN_STORE_ID, false)
	->load();

foreach ($valuesCollection as $item) {
	$values[$item->getValue()] = $item->getId();
}

3. Make your choice – DROPDOWN

$product->setColor( $values['Blue'] ); // just do whatever you need to code 'Blue' instead of hard-coding it

3. Make your choices – MULTISELECT

$product->addData( array(
	'color' => $values['Blue'] .','. $values['Red'] .','. $values['Black']  // just putting together a comma-separated list of values
) );

4. Save the product

$product->save();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值