20

我一直在从 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()调用失败并导致此错误。有谁知道为什么会发生这种情况以及如何获得颜色选项?

谢谢!

4

5 回答 5

66

看起来您自己初始化属性,而不是使用 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但没有明确定义它的人(颜色、制造商等)。

以下代码片段应该在您的安装中完美运行:

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

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

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

于 2010-11-09T23:44:29.087 回答
7

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

$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);
于 2013-04-17T00:31:14.767 回答
5
$attribute = Mage::getModel('eav/config')->getAttribute('customer','cateinterest');
$options = $attribute->getSource()->getAllOptions();
于 2012-06-19T12:19:52.310 回答
2
<?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
于 2019-03-14T11:21:51.303 回答
-1

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

于 2010-10-22T12:39:05.557 回答