【问题标题】:Get a list of attribute options from Magento从 Magento 获取属性选项列表
【发布时间】:2011-04-28 23:55:50
【问题描述】:

我一直在像这样从 Magento 获取属性选项:

<?php

if ($attribute->usesSource()) {
    $options = $attribute->getSource()->getAllOptions(false);
}

?>

在我尝试获取内置“颜色”属性的选项之前,它一直运行良好——我收到以下错误:

PHP Fatal error:  Call to a member function setAttribute() on a non-object in app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php on line 374

getSource() 调用似乎失败并导致此错误。有谁知道为什么会发生这种情况以及如何获得颜色选项?

谢谢!

【问题讨论】:

  • 您是否能够使用 xdebug 和您的 IDE 对其进行实时调试?您可能可以深入了解 $attribute->getSource() 调用以查看其中的失败之处。我不知道为什么color 应该与其他属性有任何不同。

标签: php attributes magento multi-select


【解决方案1】:

看起来是你自己初始化属性,而不是使用Magento属性初始化过程:

Mage::getSingleton('eav/config')
    ->getAttribute($entityType, $attributeCode)

因为从 1.4.x 开始,Magento 对目录和客户模型具有单独的属性模型,并且 catalog_product 的默认源模型的定义现在从 EAV 属性模型 (Mage_Eav_Model_Entity_Attribute) 移动到目录一 (Mage_Catalog_Model_Resource_Eav_Attribute)。

因此,某些目录属性不适用于 EAV 属性模型。特别是那些使用Mage_Eav_Model_Entity_Attribute_Source_Table 但没有明确定义(颜色、制造商等)的人。

以下代码 sn-p 应该可以在您的安装中完美运行:

$attribute = Mage::getSingleton('eav/config')
    ->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'color');

if ($attribute->usesSource()) {
    $options = $attribute->getSource()->getAllOptions(false);
}

顺便说一下Mage_Eav_Model_Config 模型有很多有用的方法,可以在你的开发中使用,所以不要犹豫,看看这个模型。

【讨论】:

  • 谢谢。除了答案之外,在处理“catalog_product”时,它使用 Mage_Eav_Model_Entity_Attribute_Source_Table 类,参数为:getAllOptions($withEmpty = true, $defaultValues = false)。再次感谢您。
【解决方案2】:

如果resource_model为空,上述代码不起作用。以下 sn-p 完成了这项工作:

$attribute = Mage::getModel('eav/entity_attribute')->loadByCode(Mage_Catalog_Model_Product::ENTITY, 'YOUR_ATTRIBUTE_CODE');

/** @var $attribute Mage_Eav_Model_Entity_Attribute */
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getId())
->setStoreFilter(0, false);

【讨论】:

  • 请考虑此解决方案不关心属性值排序顺序。 $attribute->getSource()->getAllOptions(false) 确实
【解决方案3】:
$attribute = Mage::getModel('eav/config')->getAttribute('customer','cateinterest');
$options = $attribute->getSource()->getAllOptions();

【讨论】:

  • 请在您的答案中添加更多详细信息
  • 这适用于不使用上述方法填充的 eav 属性
【解决方案4】:
<?php
  //Possible color value
  $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'color'); //"color" is the attribute_code
  $allOptions = $attribute->getSource()->getAllOptions(true, true);
  foreach ($allOptions as $instance) {
    $id = $instance['value']; //id of the option
    $value = $instance['label']; //Label of the option

【讨论】:

  • 您能否edit您的答案并添加一些解释为什么/如何您的代码解决问题?
【解决方案5】:

抱歉,答案不完整,但请查看数据库,特别是在 backend_model 列中。在我将此字段设置为与这方面的某些系统字段匹配之前,我似乎记得遇到过同样的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多