Magento – How to Auto-generate the Product URL key During Import

avs-fastsimpleimportee-1.13.0.2import

We are importing products using a PHP script using AvS_FastSimpleImport which is an extension of Mage_ImportExport.

The CSV files / array do not contain the field url_key.

So currently, this value is empty for the products.

We would like to have the URL key auto generated, just as if we enter a product manually in the backend and leave the field empty.

The script already contains a part to load admin events:

Mage::getConfig()->loadEventObservers('adminhtml');
Mage::app()->addEventArea('adminhtml');

Edit This bug is fixed in EE 1.13.1.0

Best Answer

A basic solution seems to be to set the url_key column to the product name.

This will run through \Mage_Catalog_Model_Attribute_Backend_Urlkey_Abstract::beforeSave which automatically formats the URL key properly (removing spaces and so on).

I would actually expect \Enterprise_Catalog_Model_Product_Attribute_Backend_Urlkey::beforeSave to be used during the export, because we are on Enterprise, which is not the case.

Even if the Enteprise-only method would be called during import, this would not work, because it checks the database for duplicate URL keys - which is not yet updated during that stage of the import.

Solution: After importing, detect missing URL keys using:

$urlKeyMissing = Mage::getModel('catalog/product')->getCollection()
    ->addWebsiteFilter($website)
    ->addAttributeToFilter('url_key',  array('null' => ''), 'left');

and update these products (load, setDataChanged, save).

In addition I am setting the following in the config.xml of my import module (the standard import-export is disabling the URL key checks)

<global>
    <importexport>
        <import>
            <catalog_product>
                <attributes>
                    <url_key>
                        <backend_model>enterprise_catalog/product_attribute_backend_urlkey</backend_model>
                    </url_key>
                </attributes>
            </catalog_product>
        </import>
    </importexport>
</global>