Magento – Programmatically create a Smart Category Rules

categorymagento-enterpriseprogrammaticallyrulesscript

I was following this guide from inchoo for programmatically creating 50+ categories, but then I discovered this Enterprise feature, “Smart Category Rules”, and would like to use this approach instead. My question is, how do I create these smart categories programmatically using a script?

Best Answer

I was digging through this today and it's not easy to untangle. The way smart categories have been designed did not take into account any easy way for their creation programmatically via a migration script.

The merchandiser data is completely compartmentalized from the category model and there are observers which listen for category saves in the admin and kick off merchandiser handlers which ingest the POST data from the visual merchandiser tab.

The added complexity lies in the data being store as serialized arrays in the database with the keys having been generated by the Magento backend.

For instance:

Array
(
    [0] => Array
        (
            [category_id] => 18
            [heroproducts] =>
            [attribute_codes] => product_type
            [smart_attributes] => a:1:{s:18:"_1452698469143_143";a:3:{s:9:"attribute";s:3:"180";s:5:"value";s:4:"1190";s:4:"link";s:2:"OR";}}
            [ruled_only] => 0
            [automatic_sort] => none
        )

)

... where smart_attributes unserializes to...

Array
(
    [_1452698469143_143] => Array
        (
            [attribute] => 180
            [value] => 1190
            [link] => OR
        )

)

One (admitadly terrible) option might be to generate the smart category, and then use the data in a migration script that instantiates the merchandiser/merchandiser resource model and inserts it via the insertCategoryValues method. That's how the core handle it, at any rate (you can see it in action in:

// app/code/community/OnTap/Merchandiser/etc/config.xml

<catalog_category_save_after>
    <observers>
        <merchandiser_catalog_category_prepare_save>
            <class>merchandiser/adminhtml_observer</class>
            <method>categorySaveAfter</method>
        </merchandiser_catalog_category_prepare_save>
    </observers>
</catalog_category_save_after>

Which kicks off the categorySaveAfter method where the configured VM settings are stored.

app/code/community/OnTap/Merchandiser/Model/Adminhtml/Observer::categorySaveAfter()

I have an email out to the OnTap team to see if they have any best-practice suggestions for handling the creation of VM rules for use in migration scripts. If they reply with anything useful, I'll post it here.

Related Topic