Stopping product saving process in observer

后端 未结 5 1547
猫巷女王i
猫巷女王i 2021-01-06 05:07

I am currently developing a module working with the product edit in the backend. Its purpose is to retrieve categories the product belongs to and populate an attribute (the

5条回答
  •  死守一世寂寞
    2021-01-06 06:03

    It's always a crap shoot as to which sections of Magento support this, but throwing an exception is often the prescribed way of telling Magento that something went wrong. The layers higher up the stack are set to catch these exceptions and use them to go back to the form and display an error message. Give this a try

    Mage::throwException(Mage::helper('adminhtml')->__('You totally failed at that.'));
    

    If you take a look at the Adminhtml module's Catalog/ProductController.php (1.5, but I'd assume a similar format in previous versions)

    function saveAction()
    {
        ...
        $product = $this->_initProductSave();
    
        try {
            $product->save();
            $productId = $product->getId();
        ...
    }
    

    The _initProductSave method is where the catalog_product_prepare_save event is fired. Since this is outside the saveAction's try/catch block, the exception won't be caught (as described in the comments below).

    You'll need to move you validation code into the product model's before save event (catalog_product_save_before). Doing that should let you throw an exception and have the admin display the error message and represent the form for editing.

提交回复
热议问题