我已經嘗試了 5 個小時但沒有成功......我有一個 Symfony 5.3 應用程式并實作了一個與物體無關的搜索頁面。完美運行,但是在創建通用可用性測驗時,引數不會傳遞給控制器??。我試過用 $_POST 陣列進行模擬,將陣列傳遞給 $client->request() 的第三個引數,但結果總是顯示執行了 GET 方法并且該引數未包含在請求中。
表格是這樣的:
<form class="form-search" action="{{ path('search_result') }}" method="post">
<input name="searchwords" placeholder="{{ 'search.placeholder'|trans }}" type="text" hljs-string">">
<button type="submit" hljs-string">"><i hljs-string">"></i></button>
</form>
在我的控制器中,可以使用以下命令訪問引數“searchwords”:
$vars = Request::createFromGlobals();
$temp_searchwords = explode(' ', $vars->get('searchwords'));
現在我正在嘗試在通用可用性測驗期間傳遞引數
$crawler = $client->request('POST', '/de/search/result', ["searchwords" => "test"]);
結果顯示使用了 GET 方法,并且沒有將引數傳遞給 Controller。我也試過用 $_POST 系統變數來模擬:
$_POST = ["searchwords" => "test strings"]
Request::createFromGlobals(); 在我的控制器中沒有給出任何引數,可能是因為使用了 GET 方法而不是我的 $client->request() 呼叫中請求的“POST”。
從官方 Symfony 5.3 檔案中進行的另一次嘗試也失敗了,引數未傳遞給我的控制器:
$buttonCrawlerNode = $crawler->selectButton('');
$form = $buttonCrawlerNode->form();
$form['searchwords'] = "test string";
// at this point the $form object contains the parameter "searchwords" and the value "test string"
$crawler = $client->submit($form);
問題:如何將引數傳遞給控制器??并在測驗中強制執行“POST”請求?如上所述,搜索在真實的瀏覽器環境中運行良好。
uj5u.com熱心網友回復:
如果有人發現自己處于這種情況:
我通過以下函式呼叫了 post 變數“searchword”。
$vars = Request::createFromGlobals();
$searchwords = explode(' ', $vars->get('searchwords'));
但是,這僅適用于瀏覽器,因為 WebTest 創建了一個請求物件,而無需通過全域變數進行轉移。
真正的解決方案是在您的控制器函式中自動裝配請求物件并將其用于引數檢索:
public function searchResultAction($_locale, DuddeSearch $ds, Request $request)
{
[...]
$searchwords = explode(' ', $request->get('searchwords'));
}
這個問題是我初學者的錯誤。Symfony 的“最佳實踐”中明確且突出地提到了自動裝配。唯一的困難是我的解決方案在瀏覽器中完美運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/360613.html
