【问题标题】:How to acces value from route in symfony2如何从 symfony 2 中的路由访问值
【发布时间】:2017-03-24 12:40:24
【问题描述】:

我有一些新手问题。我如何从我的路线访问特定值。 这是我的代码:

/**
 * Catch controller.
 *
 * @Route("catch")
 */
class CatchController extends Controller
{
    /**
     * @Route("/{id}")
     * @Method({"GET"})
     * @ParamConverter("advertisement", class="AffiliateBundle:Advertisement")
     */
    public function goAction(Advertisement $advertisement)
    {
        //$advertisementId = $advertisement->getId();
        //die($advertisementId);
        //Creating new Lead
        $elo = $advertisement->getId();
        die($elo);
        $lead = new Lead();
        $lead ->setCreatedAt(new \DateTime());
        $lead ->setUpdatedAt(new \DateTime());
        //$lead ->setAdvertisement($advertisementId);
        $add = $this->getDoctrine()->getManager();
        $add->persist($lead);
        $add->flush();            
        //Taking id of the created lead
        $leadId = $lead->getId();
        //Saving cookie in user's browser
        $cookieValue = array(
            'name' => 'leadcookie',
            'value' => $leadId
        );
        $cookieLead = new Cookie($cookieValue['name'], $cookieValue['value']);
        $response = new Response();
        $response->headers->setCookie($cookieLead);
        //Redirecting user to advertisement url.
        $advertisementUrl = $advertisement->getUrlPattern();
        return $this->redirect($advertisementUrl);

    }

当我在浏览器中调用 affiliate/catch/3 时,我可以通过它的方法从我的广告实体中获取每个属性。像 UrlPattern、RRSO 等。 但是我需要获取此广告的 ID,当我在控制器中使用 getId() 而不是 3 时,我什么也得不到。我该怎么做?

【问题讨论】:

  • 你的控制器的常用路由是什么?是affiliate/catch/?
  • 是的,它是affiliate/catch/{id of advertisement number}
  • 那么如果数据库中有广告ID,那么您肯定会通过$advertisement->getId()获得广告ID
  • 它没有给我任何错误,但是当我尝试使用 print_r 时,我什么也没得到。
  • goAction(Advertisement $advertisement,$id) 应该可以解决问题。但就像@MaulikSavaliya 所说,如果 getId 不起作用,那么你还有其他事情要做。

标签: php symfony routes


【解决方案1】:

你可以试试这个:

/**
 * @Route("/{id}", requirements={"id" = "\d+"})
 * @Method({"GET"})
 * @ParamConverter("advertisement", class="AffiliateBundle:Advertisement")
 */
public function goAction(Advertisement $advertisement, $id) //add $id here
{
    //your id is stocked in $id, do what you want with it
    //I had "requirements" as your id must be a number
    //...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    相关资源
    最近更新 更多