2

我创建了一个 Observer 来监控事件subscriber_save_before。在这个观察者中,我处理了一个新字段,该字段的值被保存,但如果发生一些错误,我希望不保存记录并仅显示我的错误消息。throwException 似乎不能解决问题。我认为唯一可行的方法是强制电子邮件字段为空,但无法实现这一点。在subscriberController.php(法师核心)我有这个:

$email = (string) $this->getRequest()->getPost('email');

        try {
            if (!Zend_Validate::is($email, 'EmailAddress')) {
                Mage::throwException($this->__('Please enter a valid email address.'));
            }

这是我的代码(不工作):

    public function NewsletterSaveSubscriber($observer)
{
    $subscriber = $observer->getEvent()->getSubscriber();
    $name = Mage::app()->getRequest()->getParam('subscriber_name');



    // server side validation
    // no name specified
    if (!Zend_Validate::is(trim($name), 'NotEmpty')) {

        $session = Mage::getSingleton('core/session');

        try {
            Mage::throwException(Mage::helper('newsletter')->__('The name field cannot be empty!'));
        } catch (Mage_Core_Exception $e) {
            $session->addException($e, Mage::helper('newsletter')->__('There was a problem: %s', $e->getMessage()));
        }
     $observer->getRequest()->setPost('email', ''); // this code doesn't work
     Mage::app()->getRequest()->setPost('email', ''); // this too 

          // Ohh nooo! The subscriber is stored :-(
        return $this;
    }


    // save the name
    $name = htmlspecialchars($name);
    $subscriber->setSubscriberName($name);
    return $this;
}
4

1 回答 1

1

这将解决您的问题:

//Error Message
$session = Mage::getSingleton('core/session');
$session->getMessages(true);
$session->addError(Mage::helper('cartware_automaticreview')->__('Could´t save.'));  

// Ohh nooo! The subscriber is not stored :)            
$controller = $observer->getControllerAction()->setFlag('',Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH,true);
$controller->getResponse()->setRedirect(Mage::app()->getRequest()->getServer('HTTP_REFERER'));
return;

祝你好运!

于 2013-06-27T23:00:29.780 回答