好的。所以你可以把兩條路線都放到一個方法上。您的註釋將被組合並且是這樣的:
/**
* @Route("/{slugHoroscope}", name="horoscope_homepage")
* @Route("/{slugHoroscope}/{slugZodiac}.{_format}", name="horoscope_detail", defaults={"_format": "html"})
將您的參數放在相同的註釋中。
然後將params添加到您要使用的任何一種方法中。所以像這樣:
public function homePageAction(Horoscope $horoscope = null, HoroscopeSigne $horoscopeSigne = null, Request $request)
{
$form = $this->createForm(DateType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
dump($data);
}
}
然後,你將不得不做一些邏輯的路線和參數。例如:
$request = $this->container->get('request');
$routeName = $request->get('_route');
if ($routeName == 'horoscope_homepage) {
$template = the_template_for_the_homepage;
$params = the_parameters_for_the_homepage;
} else {
$template = the_template_for_the_other_page;
$params = the_params_for_the_other_page;
}
然後,你還必須對params做一些邏輯。例如:
if ($horoscope == null) {
//your logic
}
然後返回您的模板和參數。像這樣:
return $this->render($template, $params);
你將不得不擺弄大量的邏輯。另一種選擇是將表單邏輯提取到其他方法或服務。
如:
<?php
namespace AppBundle\Controller;
use...
**
* @Route("/horoscopes")
*/
class HoroscopeController extends Controller
{
/**
* @Route("/{slugHoroscope}", name="horoscope_homepage")
*
* @ParamConverter("horoscope", class="AppBundle:Horoscope", options={
* "mapping": {"slugHoroscope": "slug"},
* "repository_method" = "findByComplexSlug",
* "map_method_signature" = true
* })
*/
public function homePageAction(Horoscope $horoscope, Request $request)
{
$this->formMethod();
return $this->render(':horoscope:acc-horoscope.html.twig', [
'horoscope' => $horoscope,
'form' => $form->createView()
]);
}
/**
* @Route("/{slugHoroscope}/{slugZodiac}.{_format}", name="horoscope_detail", defaults={"_format": "html"})
*
* @ParamConverter("horoscopeSigne", class="AppBundle:HoroscopeSigne", options={
* "mapping": {"slugHoroscope": "slugHoroscope", "slugZodiac": "slugZodiac"},
* "repository_method" = "findByComplexSlug",
* "map_method_signature" = true
* })
*/
public function detailAction(HoroscopeSigne $horoscopeSigne)
{
$this->formMethod();
$template = $horoscopeSigne
->getHoroscope()
->getHoroscopeModele()
->getTemplatePath();
return $this->render('horoscope/'.$template, [
'horoscope' => $horoscopeSigne->getHoroscope(),
'horoscopeSigne' => $horoscopeSigne,
]);
}
private function formMethod() {
$form = $this->createForm(DateType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
dump($data);
}
}
你可以發佈你的控制器代碼嗎?我們始終使用相同的控制器方法來處理多個頁面和操作。 – ASOlivieri
@ASOlivieri好吧,現在我沒有在我的控制器中處理表單,我想在之前考慮一個更好的解決方案!如果我發現如何發佈我的代碼,我會嘗試(我是新來的,對不起) –