我可以在表单生成器中使用查询来获得symfony表单中的过滤集合吗


Can i use query in form builder to get filtered collection in symfony form

在AcmePizza BUndle中,运行良好

->add('pizza', 'entity', array(
                'class'         => 'Acme'PizzaBundle'Entity'Pizza',
                'query_builder' => function ($repository) { return $repository->createQueryBuilder('p')->orderBy('p.name', 'ASC'); },
            ))

我可以在收集中做这样的事情吗

->add('userTasks','collection',array('type' => new UserTaskType(),
                    'class'         => 'acme'myBundle'Entity'UserTask',
                    'query_builder' => function ($repository) { return $repository->createQueryBuilder('p')->orderBy('p.name', 'ASC'); },
                ))

假设您的userTasks是一个关系,您将在这里找到您的案例的答案。这些只是排序的方法,但如果您需要一些WHERE条件,它就不那么简单,但也不难。

我不得不过滤掉一些实体,解决它的关键是在实体类中创建set/get方法,返回所需的set。

在我的情况下,它看起来像这个

/**
 * Set values
 *
 * @param ArrayCollection $values
 * @return Attribute
 */
public function setCustomValues($values)
{
    $result = $this->getNotCustomValues();
    foreach ($values as $value)
    {
        $value->setAttribute($this);
        $result->add($value);
    }
    $this->values = $result;
    return $this;
}
/**
 * Get values
 *
 * @return 'Doctrine'Common'Collections'Collection
 */
public function getCustomValues()
{
    $result = new ArrayCollection();
    foreach ($this->values as $value) {
        if($value->getCustom()) {
            $result->add($value);
        }
    }
    return $result;
}

创建表单时,字段的名称为"customvalues"而不是"values"所以我的集合只包含自定义字段为true的值。

当您更新实体而没有新实体时,您通常想要过滤集合,对吗?

这是一个有效的解决方案,这是控制器(CRUD)的一个例子:

public function updateAction($id)
{
    $service = $this->getServiceRepository()->loadOne('id', $id);
    $this->checkPermission($service);
    $this->filterInventoryByPrimaryLocation($service);
    if($this->getFormHandler()->process('service_repair_service', $service, array('type' => 'update')))
    {
        $this->getEntityManager()->process('persist', $service);
        return $this->render('ServiceRepairBundle:Service:form_message.html.twig', [
            'message' => $this->trans('Service has been updated successfully.')
        ]);
    }
    return $this->render('ServiceRepairBundle:Service:form.html.twig', [
        'form' => $this->getFormHandler()->getForm()->createView(),
    ]);
}
private function filterInventoryByPrimaryLocation(Service $service)
{
    $inventory = $service->getInventory();
    $criteria = Criteria::create()
        ->where(Criteria::expr()->eq('location', $this->getUser()->getPrimaryLocation()))
        ->orderBy(array('timeInsert' => Criteria::ASC));
    $service->setInventory($inventory->matching($criteria));
}

$service=实体,$inventory=ArrayCollection($service->getInventory())

这里的关键是使用条令的标准,更多信息在这里:

http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-associations.html#filtering-集合

也可以考虑在实体本身中移动标准,在那里公开方法。当您从数据库加载它时,您可以使用条令的postLoad生命周期回调来启动该方法。当然,如果你不需要任何服务或类似的东西,把它放在实体中是可行的。

另一个解决方案可能是,如果您只需要在表单中进行筛选,那么将Form Event中的Criteria移到Form类中

如果您需要在整个项目中透明地进行集合过滤,请编写一个原则侦听器,并将代码放入postLoad()方法中。您也可以在原则侦听器中注入依赖项,但我建议注入容器本身,因为加载其他服务很慢,所以不会得到循环服务引用。

祝你好运!

我为您指明了正确的方向(我希望):

http://www.craftitonline.com/2011/08/symfony2-ajax-form-republish/

本文讨论字段依赖关系。例如,当您选择一个国家/地区时,列表中会显示属于该国家/地区的城镇。

在Symfony 2.7中,我通过在UserTaskType中执行以下操作来解决此问题:

<?php
namespace AppBundle'Form;
use Symfony'Component'Form'AbstractType;
use Symfony'Component'Form'FormBuilderInterface;
use Symfony'Component'OptionsResolver'OptionsResolver;
use Doctrine'ORM'EntityRepository;
class UserTaskType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('the_name', 'entity', array(
                'class' => 'acme'myBundle'Entity'UserTask',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('u')
                        ->where('u.id > :id')
                        ->setParameter('id', '1')
                        ->orderBy('u.username', 'ASC');
                },
            ));
    }
    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'acme'myBundle'Entity'UserTask',
        ));
    }
}

是。

在UserTaskType类中,添加以下方法。

public function getDefaultOptions(array $options)
{
    return array(
        'data_class' => 'acme'myBundle'Entity'UserTask',
        'query_builder' => function($repo) {
            return $repo->createQueryBuilder('p')->orderBy('p.name', 'ASC');
        }
    );
}