Magento loadByAttribute for Custom Category Attributes

Posted by Chris on Stack Overflow See other posts from Stack Overflow or by Chris
Published on 2010-05-21T22:58:02Z Indexed on 2010/05/21 23:00 UTC
Read the original article Hit count: 405

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?

© Stack Overflow or respective owner

Related posts about magento

Related posts about categories