我已經設定了一個 Magento 2 模塊來使用表單從用戶那里收集一些資料。提交表單后,控制器應處理該資料,然后在另一個頁面上顯示結果。我在讓控制器重定向到包含資料的結果頁面時遇到問題。這是我目前設定的:
塊檔案
vendor\MyModule\Block\Index.php
public function getManualFormAction()
{
return $this->getUrl('mamform/index/post');
}
模板檔案 vendor\MyModule\view\frontend\templates\index.phtml
<form action="<?= $block->escapeUrl($block->getManualFormAction()) ?>" >
...
</form>
控制器檔案 vendor\MyModule\Controller\Index\Post.php
public function execute()
{
$post = $this->getRequest()->getPostValue();
var_dump($post);
// handle and proccess data
// The data processed should be displayed in the Result page
}
結果控制器vendor\MyModule\Controller\Index\Result.php
public function execute()
{
$resultPage = $this->resultPageFactory->create();
return $resultPage;
}
結果模板vendor\MyModule\view\frontend\templates\result.phtml
<h1>Results appears here</h1>
模塊路由vendor\MyModule\etc\frontend\routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route frontName="mamform" id="mamform">
<module name="vendor_MyModule" />
</route>
</router>
</config>
結果布局vendor\MyModule\view\frontend\layout\mamform_index_result.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="vendor\myModule\Block\Index" name="mam_result" template="vendor_myModule::result.phtml"></block>
</referenceContainer>
</body>
</page>
目前,如果我訪問/mamform/result,我可以看到模板按預期作業。我現在如何傳遞 Post Controller 中處理的資料,并將其顯示在 Result 頁面中?
uj5u.com熱心網友回復:
您正在尋找的是重定向結果。
在您的Post控制器中,您可以像這樣創建重定向物件:
<?php
public function execute() {
$post = $this->getRequest()->getPostValue();
// handle and process data
// The data processed should be displayed in the Result page
$result = $this->resultRedirectFactory->create();
$result->setPath("path to your result controller", [$post, any_other_params]);
return $result;
}
?>
這將創建重定向結果,并將呼叫您作為第一個引數傳遞的任何控制器路由的執行方法,setPath并且該陣列將與 url 一起傳遞。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/459455.html
