阻止订阅者在观察者中保存newsletter_subscriber_save_before Magento

时间:2013-03-18 22:26:16

标签: magento magento-1.7

我创建了一个Observer来监视事件subscriber_save_before。在这个观察者中,我处理一个新字段,保存了该字段的值,但是如果发生了一些错误,我想要记录不要保存并只显示我的错误消息。 throwException似乎没有做到这一点。我认为唯一可行的方法是强制将电子邮件字段设为null但无法实现此目的。 在subscriberController.php(Mage Core)中我有这个:

$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;
}

1 个答案:

答案 0 :(得分:0)

这将解决您的问题:

//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;
祝你好运!