Magento 2-将产品添加到购物车时,直接转到结帐页面
我正在编写一个扩展,它允许在单击产品页面上的“添加到购物车”按钮时直接转到结帐页面。我为Magento 1找到了一个解决方案,并尝试将其应用于Magento 2。这是我的档案: 文件etc/frontend/events.xml:Magento 2-将产品添加到购物车时,直接转到结帐页面,magento,magento2,magento-2.0,Magento,Magento2,Magento 2.0,我正在编写一个扩展,它允许在单击产品页面上的“添加到购物车”按钮时直接转到结帐页面。我为Magento 1找到了一个解决方案,并尝试将其应用于Magento 2。这是我的档案: 文件etc/frontend/events.xml: <?xml version="1.0" encoding="utf-8" ?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLo
<?xml version="1.0" encoding="utf-8" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_add_product_complete">
<observer
name="mycompany_go_to_checkout"
instance="MyCompany\GoToCheckout\Observer\GoToCheckout" />
</event>
</config>
我应该更改或添加什么以使其工作
任何指导都将不胜感激。您必须使用以下代码从Magento2中的观察者重定向
public function execute(Observer $observer)
{
$redirect = $observer->getEvent()->getRedirect();
$redirect->setRedirect(true)->setPath('checkout')->setArguments([]);
return $this;
}
下面是完整的工作代码。我在模块中使用了if
<?xml version="1.0" encoding="utf-8" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_add_product_complete">
<observer
name="mycompany_go_to_checkout"
instance="MyCompany\GoToCheckout\Observer\GoToCheckout" />
</event>
</config>
但此代码仅适用于详细信息页面。在清单页面中,它将无法工作,因为它是由Ajax管理的。那么解决办法是什么呢?简单,只需为Checkout/Controller/Cart/Add.php创建一个插件,并将您的逻辑写入该文件。Magento已经为这些设置提供了管理员设置 Magento1
Admin > System > Configuration > Checkout > Shopping Cart > After Adding a Product Redirect to Shopping Cart >YES.
Magento2
Admin-> Store ->Configuration->Sales->Checkout ->After Adding a Product Redirect to Shopping Cart
根据需要设置下拉值,对于Magento 2,请在Observer中使用此代码:
public function execute(Observer $observer)
{
$observer->getRequest()->setParam('return_url', $this->urlInterface->getUrl('checkout'));
return $this;
}
现在什么不起作用?你检查过你的观察者是否正确发射了吗?我同意Robbie的观点,检查它是否在我认为是第一步的第一个位置发射。我检查了,它发射了。我尝试了代码,并添加了一些日志输出,以遵循流程。它似乎停在第二行:
$redirect->setRedirect(true)->setPath('checkout')->setArguments([])代码>日志文件中没有其他信息。抛出异常“致命错误:未捕获错误:调用/path_to_module_observer/observer.php:100中null上的成员函数setRedirect()”我试图从产品详细信息页面重定向到签出,但这在magento 2.2.5中不起作用。你能告诉我,如何从插件重定向吗?你能告诉我实现这个代码的步骤吗?我是在magento中制作插件的新手。
Admin-> Store ->Configuration->Sales->Checkout ->After Adding a Product Redirect to Shopping Cart
public function execute(Observer $observer)
{
$observer->getRequest()->setParam('return_url', $this->urlInterface->getUrl('checkout'));
return $this;
}