phpsymfonydoctrine-ormsymfony-formssymfony2

How to use Repository custom functions in a FormType


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--'),
                ));

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;

}
}

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


Solution

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