magento getOptionId 不适用于某些标签

问题描述 投票:0回答:2

我使用下面的代码来获取

attribute set "size"
的选项 id。 如果我使用大于 9 的选项标签(即 10,12,13,14 ..),它会返回正确的 id

但是如果使用选项标签小于 10(即 5,6,7,8,9),则不起作用。

$attr = 'size';
$attribute_label = 13;
$_product = Mage::getModel('catalog/product');
$attribute_name = $_product->getResource()->getAttribute($attribute_name);

if ($attr->usesSource()) {
    echo $color_id = $attribute_name->getSource()-  >getOptionId($attribute_label);
}

示例:

当我使用选项标签 ($attribute_label = 13) 作为 13 时的输出 返回 5.

当我使用选项标签 ($attribute_label = 6) 作为 6 时的输出,它返回 6.

php magento
2个回答
1
投票

发生这种情况是因为 getOptionId() 不能很好地处理数字标签,正如本问题中所述:https://magento.stackexchange.com/questions/128445/getoptionid-method-returns-invalid-option-id

您可以做的是避免使用此方法并调整您的代码,例如:

$attribute_name = 'size';
$attribute_label = 13;
$optionId = false;
$attr = Mage::getResourceModel('catalog/product')->getAttribute($attribute_name);
if ($attr->usesSource()) {
    $options = $attr->getSource()->getAllOptions();
    foreach($options as $option) {
        if($option['label'] == $attribute_label) {
            $optionId = $option['value'];
            break;
        }
    }
}

0
投票

在我的例子中,问题是标签只显示了一个数字(8),但由于客户端数据和 Magento DB 格式不正确,实际标签是“标准(MERV 8)”,但在管理中它只显示了数字 8管理员。如果@mihai-matei 解决方案不起作用,请将所有选项转储到日志中并查看它们。

© www.soinside.com 2019 - 2024. All rights reserved.