2017-09-15 130 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', 
));