好的。所以你可以把两条路线都放到一个方法上。您的注释将被组合并且是这样的:
/**
* @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好吧,现在我没有在我的控制器中处理表单,我想在之前考虑一个更好的解决方案!如果我发现如何发布我的代码,我会尝试(我是新来的,对不起) –