Search code examples
magentomodelresourcesentity-attribute-value

Magento. How to link store_id to the attribute in the custom EAV Model


I am using this tutorial on adding new EAV Model in Magento: http://inchoo.net/ecommerce/magento/creating-an-eav-based-models-in-magento/

Everything works fine except all my attributes are saving with "store_id = 0" when I do this part of code:

$phonebookUser = Mage::getModel('inchoo_phonebook/user');
$phonebookUser->setFristname('John');
$phonebookUser->save();

I am wondering is there any clear way to set store ID on save EAV Entity Attributes.

Thanks.


Solution

  • I have override the functions in my resource model to work with store_id and it is worked for me but I suggest that this is not the best solution.

    protected function _saveAttribute($object, $attribute, $value)
    {
        $table = $attribute->getBackend()->getTable();
        if (!isset($this->_attributeValuesToSave[$table])) {
            $this->_attributeValuesToSave[$table] = array();
        }
    
        $entityIdField = $attribute->getBackend()->getEntityIdField();
    
        $data   = array(
            'entity_type_id'    => $object->getEntityTypeId(),
            $entityIdField      => $object->getId(),
            'attribute_id'      => $attribute->getId(),
            'store_id'          => $object->getStoreId(), //added this
            'value'             => $this->_prepareValueForSave($value, $attribute)
        );
    
        $this->_attributeValuesToSave[$table][] = $data;
    
        return $this;
    }
    
    protected function _getLoadAttributesSelect($object, $table)
    {
        $select = $this->_getReadAdapter()->select()
            ->from($table, array())
            ->where($this->getEntityIdField() . ' =?', $object->getId())
            ->where('store_id in (?)', array($object->getStoreId(), 0)); //added this
        return $select;
    }
    

    also I have added this code to the constructor of my entity model:

        if (Mage::app()->getStore()->isAdmin()) {
            $this->setStoreId(Mage::app()->getRequest()->getParam('store', 0));
        }
        else{
            $this->setStoreId(Mage::app()->getStore()->getId());
        }