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 Brand attribute) with the list of selected categories.
It is mandatory for the admin to select at least one category.
My module works as expected except that I don't know how to stop the saving process if the admin hasn't selected any category while editing a product.
Here is the workflow
- Administrator selects categories in the category tab in the product edit page
- Admin clicks on "Save"
- My module "observes" and gathers all categories
--> If there are selected categories
- My module's observer does its stuff to update the Brand attribute
--> Else
- My module's observer adds an error to the admin session
- My module's observer should tell Magento to stop saving the product. But how do I do that ?
The generic question would maybe be : how to pass a "stop save" argument to an observer ?
Here are a sample of my config.xml file and the method that deals with the workflow I explained above.
Thanks a lot for your help and have fun Magentoing !
config.xml
<catalog_product_prepare_save>
<observers>
<brands_product_save_observer>
<type>singleton</type>
<class>brands/observer</class>
<method>saveProductBrand</method>
</brands_product_save_observer>
</observers>
</catalog_product_prepare_save>
Observer.php
public function saveProductBrand($observer) {
$product = $observer->getProduct();
$categoryIds = $product->getCategoryIds();
if (isset($categoryIds)) {
foreach ($categoryIds as $categoryId) {
$isBrandCategory = Mage::getModel('brands/navigation')->isBrandCategory($categoryId);
if ($isBrandCategory)
$brandCategories[] = $categoryId;
}
if (isset($brandCategories)) {
$brandId = Mage::getModel('brands/navigation')->getBrand($brandCategories[0]);
if ($brandId) {
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 140);
foreach ($attribute->getSource()->getAllOptions(true, true) as $option) {
$attributeArray[$option['label']] = $option['value'];
}
$categoryName = Mage::getModel('catalog/category')->load($brandId)->getName();
$product->setData('brand', $attributeArray[$categoryName]);
}
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('catalog')->__('Please add this product to a brand in the "Categories" tab.'));
HERE SOME CODE TO TELL MAGENTO TO STOP SAVING THE PRODUCT
return;
}
}
}