How to add a category to Magento via Setup script?

前端 未结 5 1159
长发绾君心
长发绾君心 2021-01-13 05:42

I actually can add a category via setup script, the thing is for some reason some of the fields doesn\'t get set properly. Here\'s is my code

$this->start         


        
5条回答
  •  走了就别回头了
    2021-01-13 06:29

    I finally found it, I'm not sure why but those fields are not showing up properly because they were inserted for the default store (storeId=1) because my script is running in an update script. You need to use the storeId 0.

    With this information you would think that the solution would be something like :

    $this->startSetup();
    Mage::register('isSecureArea', 1);
    
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    
    $category = Mage::getModel('catalog/category');
    $category->setPath('1/2') // set parent to be root category
        ->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
        ->setName('Category Name')
        ...
        ->save();
    $this->endSetup();
    

    But this code doesn't work either. Indeed after looking into Mage::app() (Mage_Core_Model_App Line 804) I noticed a IF condition that would always return the default store if you're in a setup script.

    The trick is to fake that you're not in a setup script, my working solution is:

    $this->startSetup();
    Mage::register('isSecureArea', 1);
    
    // Force the store to be admin
    Mage::app()->setUpdateMode(false);
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    
    $category = Mage::getModel('catalog/category');
    $category->setPath('1/2') // set parent to be root category
        ->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
        ->setName('Category Name')
        ...
        ->save();
    $this->endSetup();
    

提交回复
热议问题