我有一个名为“vendor_id”的属性。我有N个产品,其中“vendor_id”作为产品的属性。当admin添加新的“供应商”实体时,将以编程方式生成“vendor_id”属性的选项。代码是这样的:
public function saveAction()
{
$data = $this->getRequest()->getPost();
$designerName = $data['title'];
$product = Mage::getModel('catalog/product');
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('attribute_code', 'vendor_id')
->load(false);
$attribute = $attributes->getFirstItem()->setEntity($product->getResource());
$myresults = array ('value'=> array('optionone'=>array($designerName)));
$attribute->setData('option',$myresults);
$attribute->save();
现在这个有效。它将为“vendor_id”属性创建一个选项,当用户添加新产品(或编辑现有产品)时,“vendor_id”的下拉列表将由我们在saveAction上创建的这些“供应商”实体填充()方法。
现在,在管理员想要编辑现有属性选项的情况下,我不想创建新选项,我想编辑现有选项。当我们更改名称/标签时,选项ID保持不变非常重要。
我已经在newAction中挂钩设置一个静态var所以在saveAction()中我们可以查看是否正在编辑或创建一个新选项:
if (null == MyController::$_editScope)
{
error_log('Need to update option attribute');
$attribute->addData($myresults);
}
问题是addData()方法就是这样做的,它会添加数据,但不会更新现有的数据。属性是:
$attribute = $attributes->getFirstItem()->setEntity($product->getResource());
以下是http://docs.magentocommerce.com/Mage_Eav/Mage_Eav_Model_Entity_Attribute.html
的一个实例其中有3x个父类我已经查看了所有这些方法,这些方法允许我编辑*或更新现有选项的名称......
答案 0 :(得分:3)
你会发现这很有用。 See complete details here
//Get the eav attribute model
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
//Load the particular attribute by id
//Here 73 is the id of 'manufacturer' attribute
$attr_model->load(73);
//Create an array to store the attribute data
$data = array();
//Create options array
$values = array(
//15 is the option_id of the option in 'eav_attribute_option_value' table
15 => array(
0 => 'Apple' //0 is current store id, Apple is the new label for the option
),
16 => array(
0 => 'HTC'
),
17 => array(
0 => 'Microsoft'
),
);
//Add the option values to the data
$data['option']['value'] = $values;
//Add data to our attribute model
$attr_model->addData($data);
//Save the updated model
try {
$attr_model->save();
$session = Mage::getSingleton('adminhtml/session');
$session->addSuccess(
Mage::helper('catalog')->__('The product attribute has been saved.'));
/**
* Clear translation cache because attribute labels are stored in translation
*/
Mage::app()->cleanCache(array(Mage_Core_Model_Translate::CACHE_TAG));
$session->setAttributeData(false);
return;
} catch (Exception $e) {
$session->addError($e->getMessage());
$session->setAttributeData($data);
return;
}