I have created custom attributes for a category in my module’s install script like so:
$attrib = array(
'type' => 'varchar',
'group' => 'My Data',
'backend' => '',
'frontend' => '',
'label' => 'My Custom Field',
'input' => 'text',
'class' => '',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'visible' => true,
'required' => false,
'user_defined' => false,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'unique' => true,
);
$installer->addAttribute(3, 'custom_field', $attrib);
The field shows up fine in the admin, and when I create the category in my script like so:
$p_category = Mage::getModel('catalog/category')
->setStoreId(0)
->load(2);
$category = Mage::getModel('catalog/category');
$category->setStoreId(0)
->setName('Test Category')
->setCustomField('abcd')
->setDisplayMode('PRODUCTS')
->setAttributeSetId($category->getDefaultAttributeSetId())
->setIsActive(1)
->setIsAnchor(1)
->setPath(implode('/',$p_category->getPathIds()))
->setInitialSetupFlag(true)
->save();
I can see the value ‘abcd’ in the Magneto admin interface. But when I call the code below:
<?php
$category = Mage::getModel('catalog/category')->loadByAttribute('custom_field', 'abcd');
print_r($category);
?>
I get no result. But if I loadByAttribute using the ‘name’ field set to ‘Test Category’, I DO get a result.
So, in the database, I looked into the catalog_category_entity_varchar table and noticed that the ‘name’ attribute had an entry for both store_id = 0 AND store_id = 1 whereas the ‘custom_field’ attribute had only an entry for store_id = 1.
When I added a store_id = 0 entry for ‘custom_field’ with the value set to ‘abcd’ in the catalog_category_entity_varchar table, loadByAttribute got the expected result.
My question is, why is the ‘name’ field getting a store_id = 0 entry in catalog_category_entity_varchar and my custom field is not?
How do I load categories by custom attributes?
I’m running 1.4.1.1 and noticed a similar issue with a custom product attribute. If you filter a collection by an attribute that attribute has to have a value for the default store as well as the store you’re interested in. You can see why if you do the following
When you look at the query in the log file you’ll see that magneto does an inner join onto the attribute table for store_id 0, so if you haven’t created a value for store zero it can’t give you a result. Seems like a bug to me, I think Magento should do a LEFT JOIN.