在Symfony2中创建一个函数

时间:2015-08-12 13:01:36

标签: symfony doctrine-orm twig

在我较旧的Symfony 1.4项目中,我可以在类中创建一个函数,例如

class Grps extends BaseGrps
{
public function getAllgroupmember()
{
    $voters = Doctrine_Core::getTable('Grps')->createQuery('g')
        ->select('v.firstname')
        ->from('Voters v')
        ->leftJoin('v.Grps g')
        ->where('g.id=?',$this->id);
    return $voters->execute();
}

}

只需在模板中轻松调用该函数,如

 <?php foreach($groups as $group): ?>
        <?php if(count($group->getAllgroupmember()) > 0): ?>
        <?php if($group->name != 'NONE'): ?>
            <tr>
                <td><?php echo $group->id ?></td>
                <td><?php echo $group->name ?></td>
                <td><?php echo number_format(count($group->getAllgroupmember())) ?></td>
            </tr>
        <?php endif ?>
        <?php endif ?>
        <?php var_dump(count($group->getAllgroupmember())) ?>
    <?php endforeach ?>   

但在Symfony 2(2.7)

中我仍然感到困惑

我尝试在存储库中创建一个函数,因为有些人告诉我在实体内创建教义查询不是一个好主意。我试过的是这个

//GrpsRepository.php

class GrpsRepository extends EntityRepository
 {
 public function getAllMemberGroups()
 {
    return $this
         ->createQueryBuilder('g')
         ->select('v.firstname')
         ->from('Voters v')
         ->join('v.Grps g')
         ->where('g.id=?',$this->id )
         ->getQuery()
         ->getResult()
    ;
 }
}

并在树枝上调用它,

{% for group in groups %}
    <tr {% if loop.index is odd %}class="color"{% endif %}>
        <td>{{ group.id }}</td>
        <td>{{ group.name }}</td>
        <td>{{ group.getAllMemberGroups()| length}}</td>
    </tr>
    {% endfor %}

但它会抛出错误

  

方法&#34; getAllMemberGroups&#34; for object&#34; Project \ Bundle \ DuterteBundle \ Entity \ Grps&#34; DuterteBundle中不存在:Voters:groups.html.twig第17行

创建函数并在树枝中调用它的正确方法是什么?

我可以从控制器创建该功能吗?

public function groupsAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $groups = $em->getRepository('DuterteBundle:Grps')->getAllVotersGroups();

    return $this->render('DuterteBundle:Voters:groups.html.twig', array(
        'groups' => $groups,
    ));
}//I used this to render and loop the groups name in twig which successfully render names.

0 个答案:

没有答案