2011-12-19 49 views
3

我已成立了一個觀察者的catalog_product_collection_load_after和下面的代碼被稱爲:Magento的AddAttributeToSelect()自定義添加的屬性(觀察員)

<?php 
class Drench_Admindetails_Model_Observer { 
    public function loadAfter($observer){ 
     $collection = $observer->getEvent()->getCollection(); 
     $collection->addAttributeToFilter('admin_id', Mage::getSingleton('admin/session')->getUser()->getUserId()); 
     foreach($collection as $item) { 
      fb($item->getAdminId()); //fb() is a firebug call 
     } 
     return $this; 
    } 
} 

正如你所看到的,我過濾的admin_id的集合,我通過以下安裝腳本創建(命名空間/模塊/資源/ Eav/Mysql4/Setup.php)。

<?php 

class Drench_Admindetails_Resource_Eav_Mysql4_Setup extends Mage_Eav_Model_Entity_Setup 
{ 
    public function getDefaultEntities() 
    { 
     return array(
      'catalog_product'      => array (
       'entity_model'      => 'catalog/product', 
       'attribute_model'     => 'catalog/resource_eav_attribute', 
       'table'        => 'catalog/product', 
       'additional_attribute_table'   => 'catalog/eav_attribute', 
       'entity_attribute_collection'  => 'catalog/product_attribute_collection', 
       'attributes'       => array (
        'admin_id'      => array (
         'group'      => '', 
         'label'      => '', 
         'type'      => 'int', 
         'input'      => '', 
         'default'     => '0', 
         'class'      => '', 
         'backend'     => '', 
         'frontend'     => '', 
         'source'      => '', 
         'global'      => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE, 
         'visible'     => false, 
         'required'     => false, 
         'user_defined'    => false, 
         'searchable'     => false, 
         'filterable'     => false, 
         'comparable'     => false, 
         'visible_on_front'   => false, 
         'visible_in_advanced_search' => false, 
         'unique'      => false 
        ) 
       ) 
      ) 
     ); 
    } 
} 

此屬性存儲添加產品的管理員。 但是,收集不是在admin_id上進行過濾,而是在觀察者方法的foreach()循環中,它返回NULL而不是返回的實際admin_id

關於爲什麼它不工作的任何想法?

+0

admin_id是一個數組? ...因爲它在你的配置? – Nasaralla 2011-12-19 16:30:05

+0

不,admin_id是一個'int',它是我添加到catalog_product的Magento EAV屬性。 – 2011-12-19 16:31:14

+0

不是我所知道的,它已被添加爲'int'我認爲(因此爲什麼type = int在數組中),我對magento開發很陌生,所以糾正我,如果我錯了,我跟着這個教程:http://www.magentocommerce.com/wiki/5_-_modules_and_development/catalog/programmatically_adding_attributes_and_attribute_sets – 2011-12-19 16:36:24

回答

5

集合加載後無法對其進行過濾。改爲使用事件catalog_product_collection_load_before。如果您嘗試在此時迭代集合,它可能會調用相同的事件並啓動無限遞歸,這將會很糟糕。

admin_id屬性可能不會被添加到產品列表的選定列中,除非該屬性的used_in_product_listing設置爲true。在加載事件之前,您可能也會成功使用$collection->addAttributeToSelect('admin_id')

+0

我的不好,我忘了提及,這只是爲管理後臺(管理產品),但因爲我用後而不是之前,它不會顯示它。現在工作絕對好!非常感謝! – 2011-12-19 17:03:42