2017-09-15 129 views
1

簡單代碼:如何將getResult對象傳遞給Twig?

/** 
    * @Route("/search") 
    */ 
    public function searchAction(Request $request) { 
    $repository = $this->getDoctrine()->getRepository(Bike::class); 

    $query = $repository->createQueryBuilder('b') 
     ->where('b.brand >= :id') 
     ->setParameter('id', '1') 
     ->getQuery(); 

    $result = $query->getResult()); 

我試圖

echo $result[0]['id']; 

保存數據的變量,但它給:

Cannot use object of type AppBundle\Entity\Bike as array 

var_dump($result[0]); 

我有一些multidimensio最終陣列

object(AppBundle\Entity\Bike)[589] 
    private 'id' => int 1 
    private 'model' => string 'XXX' (length=9) 
    private 'material' => string 'BBB' (length=6) 

我想這個數組或數組變量傳遞給template.twig

+1

你應該熟悉PHP的基礎知識,比如訪問對象屬性 –

+0

@PatrickQ謝謝,PropertyAccessor幫助了我。 :) – KKK

+0

爲什麼在這裏' - > setParameter('id','1')'id是字符串? –

回答

0
public function searchAction() { 
    $em = $this->getDoctrine()->getManager(); 
    $bike = $em->getRepository("NameOfYourBundle:Bike")->findAll(); 

    return $this->render('NameOfYourBundle:ForderName:nameOfTheView.html.twig', array('bike'=>$bike)); 
} 

現在,在您的視圖:

{% for b in bike %} 
    {% if b.id >= 1 %} 
     // now put the names of attribs you need 
    {% endif %} 
{% endfor %} 

我希望這將有助於您。

0

你真的需要閱讀symfony documentation

你D找到解決方案,如:

$this->render('default/index.html.twig', array(
'variable_name' => 'variable_value', 
));