2017-03-24 28 views
1

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

/** 
* 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我什么也没有。我应该怎么做?

+0

你是哪个控制器的通用路由?它是'affiliate/catch /'? –

+0

是的,它是'affiliate/catch/{广告号码的编号}'。 – Speedvees

+0

然后,如果广告ID可用于数据库,那么当然你会通过'$ advertisement-> getId()' –

回答

0

你可以试试这个:

/** 
* @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 
    //... 
}