为动态magento创建多选属性选项

时间:2014-11-10 21:47:38

标签: php arrays magento

我是magento的新手。我编写了用于动态创建多选属性选项的脚本。

但它为产品A指定红色选项,为产品B指定黄色选项? 我想为产品分配选项。产品A有蓝色,绿色,红色值,应该选择它。

如果该产品不存在选项且不是多选的选项,则它将调用setOrAddOptionAttribute函数来创建该选项。 但不知道我做错了什么?

谢谢你的到来。

    `<?php

$username = "admin2";
$password = "admin002";
$hostname = "10.2.30.119";
$dbhandle = mysql_connect($hostname, $username, $password);
$selected = mysql_select_db("yuvraj_test", $dbhandle);

echo 'script ..';


require_once('app/Mage.php'); //Path to Magento

umask(0);
Mage::app();

error_reporting(E_ERROR | E_PARSE); //enable error reporting
set_time_limit(0);
ini_set('memory_limit', '1024M');

Mage::setIsDeveloperMode(true);
ini_set('display_errors', (Mage_Core_Model_App::ADMIN_STORE_ID));

$products = array('65' => array("blue", "green", "red"),
    '66' => array("blue", "green", "red", "pink", "yellow"));



$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'testcolor');
if ($attribute->usesSource()) {
    $options = $attribute->getSource()->getAllOptions(false);//false for default values
}

$attrOptions = array();//key : value of options
$finalArr = array();//list of option value assign to products

foreach ($options as $k => $v) {

    $attrOptions[$v['label']] = $v['value'];

    if (in_array($v['label'], $products[65])) {
        $finalArr[$v['label']][] = 65;
    }

    if (in_array($v['label'], $products[66])) {
        $finalArr[$v['label']][] = 66;
    }
}

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

foreach ($products as $prod_id => $optArr) {

    foreach ($optArr as $val) {

        if ($attrOptions[$val]) {

            Mage::getModel('catalog/resource_product_action')->updateAttributes($finalArr[$val], array('testcolor' => $attrOptions[$val]), 0);
        } else {
            setOrAddOptionAttribute($val);
            Mage::getModel('catalog/resource_product_action')->updateAttributes($finalArr[$val], array('testcolor' => $attrOptions[$val]), 0);
        }
    }
}

function setOrAddOptionAttribute($arg_value) {

    $attribute_model = Mage::getModel('eav/entity_attribute');
    $attribute_options_model = Mage::getModel('eav/entity_attribute_source_table');
    $attribute_code = $attribute_model->getIdByCode('catalog_product', 'testcolor');
    $attribute = $attribute_model->load($attribute_code);
    $attribute_options_model->setAttribute($attribute);
    $options = $attribute_options_model->getAllOptions(false);
    if (!$value_exists) {
        $attribute->setData('option', array(
            'value' => array(
                'option' => array($arg_value, $arg_value)`enter code here`
            )
        ));
        $attribute->save();
    }
    return true;
}

exit();
?>

0 个答案:

没有答案