magento 后台取产品自定义的select(下拉菜单)字段

来源:互联网 发布:给游戏做美工需要什么 编辑:程序博客网 时间:2024/05/21 17:11
例如我在后台 添加自定义的下拉菜单 假设是 opt
重写 core 文件的
Mage\Adminhtml\Block\Catalog\Product\Grid.php

// 错误的方法

protected function _prepareCollection()    {        $store = $this->_getStore();        $collection = Mage::getModel('catalog/product')->getCollection()            ->addAttributeToSelect('sku')            ->addAttributeToSelect('name')            ->addAttributeToSelect('opt')             ->addAttributeToSelect('attribute_set_id')            ->addAttributeToSelect('type_id');            ...

之后 在 _prepareColumns 方法中
添加addColumn

第一种:
$this->addColumn('opt',            array(                'header'=> Mage::helper('catalog')->__('Options'),                'width' => '80px',                'index' => 'opt',            ));

这种显然是不正确的,这么写你会发现 在grid 中显示的只是 下拉菜单里的 value 值,且搜索处是个text 类型 不是一个select


第二种:

先定义方法:
protected function _getAttributeOptions($attribute_code)    {        $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attribute_code);        $options = array();        foreach( $attribute->getSource()->getAllOptions(true, true) as $option ) {            if($option['value'] == ''){                continue;            }            $options[$option['value']] = $option['label'];        }        return $options;    }

然后是
$this->addColumn('opt',            array(                'header'=> Mage::helper('catalog')->__('Options'),                'width' => '80px',                'index' => 'opt',                'type'  => 'options',                'options' => $this->_getAttributeOptions('opt'),            ));

这时候 去后台管理产品的地方就可以看到相应产品的 opt 属性取出来了,但是 试一下过滤(搜索)功能,

过滤status type  等等都好用唯有过滤 name时候 这个选项的值都没了。。。。

于是去网上查资料 发现另一种定义 _getAttributeOptions 函数的方法

protected function _getProductAttributeOptions($attributeName) {    $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product',$attributeName);    /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */           $attributeOptions = $attribute->getSource()->getAllOptions();    $options = array();    // options in key => value Format bringen    foreach ($attributeOptions as $option) {        $options[number_format($option['value'], 4, '.', '')] = $option['label'];    }           return $options;       }
结果 过滤name的时候好好的 其他的时候都不正常了。 具体 你可以打印出来这两种取法的
sql 语句 就可以大概发现这里面的差别。 (其实我没大明白为什么会这样 - -!)

解决办法 只需要我们在_prepareCollection函数应该使用下面的方法取出 opt 属性

$collection->joinAttribute('vendor_code', 'catalog_product/vendor_code', 'entity_id', null, 'left');
注意 使用的是left 使用inner 只会取出 opt 属性有值的产品,除非你的这个选项是必填项。











0 0