How to add a category to Magento via Setup script?

前端 未结 5 1162
长发绾君心
长发绾君心 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:31

    I ran into the same issue when updating a category via a data install script. The solution provided in the accepted answer did work for updating the category, but can be improved upon as follows:

    • In the solution, the user that triggers the update script is forced to the admin environment. This can be remedied by saving the current store id and switching back at end of the script.
    • It doesn't seem that adding isSecureArea to the registry or disabling update mode had any use (at least for the use case of updating a category).

    I ended up with the following data install script for updating a category (in this example, a category is loaded by name, after which the name is updated):

    startSetup();
    
        //Switch to admin store (workaround to successfully save a category)
        $originalStoreId = Mage::app()->getStore()->getId();
        Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    
        //update category
        $category = Mage::getModel('catalog/category')
            ->loadByAttribute('name', 'OLD_CATEGORY_NAME');
        if ($category) {
            $category
                ->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
                ->setName('NEW_CATEGORY_NAME')
                ->save();
        }
    
        //Set store to original value
        Mage::app()->setCurrentStore($originalStoreId);
    
        $this->endSetup();
    ?>
    

提交回复
热议问题