停止Magento事件观察员结账的正确方法是什么?

ren*_*nat 2 php magento

我在事件checkout_controller_onepage_save_shipping_method期间验证运费报价,如果验证失败,我想将用户发送回运送方式选择,但我还想显示一条消息,说明它失败的原因.Magento有办法内置吗?

我已经在验证数据,我只是缺少重定向到发货方式和显示消息的方式.

Ala*_*orm 9

(这些都不是经过测试的代码,但概念可以让你到达你需要去的地方)

Magento是由一群软件工程师运营的项目.当您与一群软件工程师合作时,文档就是代码.

即每当你需要与Magento做一些共同的事情时,请观察核心团队是如何做到这一点的,考虑到你应该限制观察者,覆盖和新代码,因为你不能与核心团队讨论你的变化.

看一页结帐控制器的IndexAction方法

app/code/core/Mage/Checkout/controllers/OnepageController.php
public function indexAction()
{
    if (!Mage::helper('checkout')->canOnepageCheckout()) {
        Mage::getSingleton('checkout/session')->addError($this->__('The onepage checkout is disabled.'));
        $this->_redirect('checkout/cart');
        return;
    }
    ... 
Run Code Online (Sandbox Code Playgroud)

Magento允许您向会话对象添加错误,该错误将在下一个请求时由消息传递块处理.

Mage::getSingleton('checkout/session')->addError($this->__('The onepage checkout is disabled.'));
Run Code Online (Sandbox Code Playgroud)

处理错误的那个.接下来,有重定向.这发生在这里

$this->_redirect('checkout/cart');
Run Code Online (Sandbox Code Playgroud)

由于您是从观察者调用此代码,因此您无权访问此方法.但是,如果您检查控制器

/**
 * Retrieve request object
 *
 * @return Mage_Core_Controller_Request_Http
 */
public function getRequest()
{
    return $this->_request;
}
...
protected function _redirect($path, $arguments=array())
{
    $this->getResponse()->setRedirect(Mage::getUrl($path, $arguments));
    return $this;
}
Run Code Online (Sandbox Code Playgroud)

您可以使用响应对象查看它.Magento使用全局响应对象(类似于Zend和其他Web框架)来处理发送回浏览器的内容(即重定向头).您可以通过以下方式获取对同一对象的引用

Mage::app()->getResponse()
Run Code Online (Sandbox Code Playgroud)

并且可以执行类似的重定向

Mage::app()->getResponse()->setRedirect(Mage::getUrl('checkout/cart'));
Run Code Online (Sandbox Code Playgroud)


clo*_*eek 9

Alan Storm的答案一如既往,提供了丰富的信息和启发.但在这种情况下,单页结账主要是AJAX忽略了会话错误消息,在离开结账页面之前你不会看到它.

saveShippingMethodAction以下行中:

$result = $this->getOnepage()->saveShippingMethod($data);
Run Code Online (Sandbox Code Playgroud)

...然后$ result是JSON编码的.如果您覆盖Mage_Checkout_Model_Type_Onepage::saveShippingMethod以执行检查然后控制返回的内容,您可以插入一条错误消息,该消息将返回到浏览器并在弹出窗口中显示给用户.

您的覆盖可能如下所示:

public function saveShippingMethod($shippingMethod)
{
    if ($this->doesntApplyHere()) {
        return array('error' => -1, 'message' => $this->_helper->__('Explain the problem here.'));
    }
    return parent::saveShippingMethod($shippingMethod);
}
Run Code Online (Sandbox Code Playgroud)