如何在 FormType 中使用 Repository 自定义函数

2023-12-23

我面临的问题是我必须以包含所有父实体(类别实体)的表单创建一个选择框。现在我设法做到这一点:

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

正如你所看到的,我传递的第一个参数是当前的category.id(类别不能是它自己的父级),第二个参数是父级id,因为我想要该父级的所有子级。这很好用,但它并没有给我父母的孩子的孩子。 我创建了一个具有返回所有子项的递归函数的 CategoryRepository:

<?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) 函数?


我把答案贴出来:Symfony2 选择字段不起作用 https://stackoverflow.com/questions/16463926/symfony2-choice-field-not-working/16478110#16478110。谢谢redbirdo https://stackoverflow.com/users/302002/redbirdo.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 FormType 中使用 Repository 自定义函数 的相关文章

随机推荐