如何在FormType中使用Repository自定义函数 [英] How to use Repository custom functions in a FormType

查看:195
本文介绍了如何在FormType中使用Repository自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是我必须创建一个包含所有父实体(类实体)的窗体中的选择框。现在我设法这样做:

The problem I'm facing is I have to create a selectbox in a form that holds all the parent entities (Category Entity). Now i managed to do this with:

$builder->add('parent', 'entity', array(
                'class' => 'KprCentarZdravljaBundle:Category',
                'query_builder' => function($repository) use ($param, $catID) { 
                                        return $repository->createQueryBuilder('p')
                                                ->where('p.id != :id AND p.parent = :parent')
                                                ->setParameters(array('id' => $param, 'parent' => $catID));},
                'property' => 'name',
                'required' => false,
                'attr'   =>  array('data-placeholder' => '--Izaberite Opciju--'),
                ));

你可以看到我通过2个参数首先是当前的category.id(一个类别不可能是它自己的父母),另一个是父ID,因为我想要父母中的所有孩子。这样做很好,但不给我父母的孩子的孩子。
我创建了一个带有递归函数的CategoryRepository,它返回所有的子代码:

As u can see i pass 2 arguments first is the current category.id(a category cant be its own parent) and a second which is a parent id, because i want all the children from that parent. This works nice but it doesn't give me the parents children's children. I created a CategoryRepository with a recursive function that returns all the children:

<?php

namespace Kpr\CentarZdravljaBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Kpr\CentarZdravljaBundle\Entity\Category;

class CategoryRepository extends EntityRepository
{
public function findByParenting($parent)
{
    $qb = $this->getEntityManager()->createQueryBuilder();

    $qb->add('select', 'cat')
       ->add('from', 'KprCentarZdravljaBundle:Category cat')
       ->add('where', 'cat.parent = :parent')
       ->setParameter('parent', $parent);
    // $qb instanceof QueryBuilder
    $query = $qb->getQuery();
    $results = $query->getResult();
    foreach($results as $result){
        if($result->getParent()){
            $newResult = $this->findByParenting($result->getId());
            $results = array_merge($results, $newResult);
        }
    }
    return $results;

}
}

如何使用findByParenting $ parent)function in a entity field?

How can I use the findByParenting($parent) function in a entity field?

推荐答案

我发布了答案: Symfony2选择字段不工作。感谢 redbirdo

I posted the answer: Symfony2 choice field not working. Thanks redbirdo.

这篇关于如何在FormType中使用Repository自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆