Her*_*tin 4 php save magento abort observer-pattern
我目前正在开发一个在后端使用产品编辑的模块.其目的是检索产品所属的类别,并使用所选类别列表填充属性(Brand属性).
管理员必须至少选择一个类别.
我的模块按预期工作,但如果管理员在编辑产品时没有选择任何类别,我不知道如何停止保存过程.
这是工作流程
- >如果有选定的类别
- >其他
通用问题可能是:如何将"停止保存"参数传递给观察者?
以下是我的config.xml文件示例以及处理我上面解释的工作流程的方法.
非常感谢您的帮助,并享受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>
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ala*_*orm 15
对于Magento的哪些部分支持这一点总是一个废话,但抛出异常通常是告诉Magento出错的规定方式.堆栈上方的层设置为捕获这些异常并使用它们返回到表单并显示错误消息.试一试
Mage::throwException(Mage::helper('adminhtml')->__('You totally failed at that.'));
Run Code Online (Sandbox Code Playgroud)
如果你看看Adminhtml模块的Catalog/ProductController.php(1.5,但我假设在以前的版本中有类似的格式)
function saveAction()
{
...
$product = $this->_initProductSave();
try {
$product->save();
$productId = $product->getId();
...
}
Run Code Online (Sandbox Code Playgroud)
该_initProductSave方法catalog_product_prepare_save是触发事件的地方.由于这是在saveActiontry/catch块之外,因此不会捕获异常(如下面的注释中所述).
您需要在保存事件(catalog_product_save_before)之前将验证代码移动到产品模型中.这样做应该让你抛出异常并让管理员显示错误消息并表示要编辑的表单.