在Magento中以编程方式更新/编辑属性选项


Programmatically updating/editing an attribute's option in Magento

我有一个名为"vendor_id"的属性。我有N个将"vendor_id"作为产品属性的产品。当管理员添加一个新的"供应商"实体时,以编程方式生成"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()方法上创建的这些"vendor"实体填充。

现在,在管理员想要编辑现有属性选项的情况下,我不想创建一个新选项,我想要编辑一个现有的选项。当我们更改名称/标签时,选项ID保持不变是很重要的。

我已经在newAction中设置了一个静态变量,所以在saveAction()中我们可以检查我们是否正在编辑或创建一个新的选项:

    if (null == MyController::$_editScope)
    {
        error_log('Need to update option attribute');
        $attribute->addData($myresults);
    }

问题是addData()方法就是这样做的,它添加数据,但不更新现有的on。属性为:

    $attribute = $attributes->getFirstItem()->setEntity($product->getResource());

是:http://docs.magentocommerce.com/Mage_Eav/Mage_Eav_Model_Entity_Attribute.html

的一个实例

它有3个父类,我已经通过他们所有的方法,将允许我编辑*或更新*一个现有的选项的名称…

您会发现这很有用。

//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;
}