在我的搜索过滤器(FormBuilder(中,为了返回过滤结果的列表,我有一个与对象相关的表单(多个复选框(。它不起作用。 我想我的存储库中有一个问题,无法获得数组与对象结果。
<?php
namespace AdminBundleController;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyBridgeDoctrineFormTypeEntityType;
use SymfonyComponentFormExtensionCoreTypeEmailType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormExtensionCoreTypeTextareaType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentValidatorConstraints as Assert;
use AdminBundleEntityProducts;
use AdminBundleFormProductsType;
class ProductsController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$form = $this->createFormBuilder()
->add('category', 'entity', array(
'class' => 'AdminBundle:Category',
'label' => false,
'choice_label' => 'name',
'required' => false,
'expanded' => true,
'placeholder' => 'Tous',
'multiple' => true
))
// ...
;
这是我的存储库:
<?php
namespace AdminBundleRepository;
class ProductsRepository extends DoctrineORMEntityRepository
{
public function ListAll($data)
{
$query = $this->createQueryBuilder('a')->orderBy('a.updated','DESC');
// CATEGORY
if($data['category'] !== null)
{
$query
->innerJoin('a.category', 'cat')
->andWhere('cat.id = :catid')
->setParameter('catid', $data['category'])
;
/*
$query
->leftJoin('a.category', 'category')
->setParameter('category', $data['category'])
;
*/
}
// ...
}
}
此存储库仅适用于单个选择:multiple => false
。 当我设置multiple => true
时,我收到有关对象与数组的SQL冲突。
如何处理多个复选框的存储库?
您必须使用 ChoiceType 而不是 entityType
class CategoryRepository extends DoctrineORMEntityRepository
{
public function getForSearch()
{
$qb = $this->createQueryBuilder('category');
$qb->orderBy('category.name');
$query = $qb->getQuery();
$results = $query->getResult();
$categories = array();
foreach ($results as $category) {
$categories[$category->getName()] = $category->getId();
}
return $categories;
}
在形式上
$categories = $em->getRepository(Category::class)->getForSearch();
->add('categories', ChoiceType::class, array(
'choices' => $categories,
'required' => false,
'placeholder' => 'Select',
))
在控制器中:
if ($search_form->isSubmitted() && $search_form->isValid()) {
$data = $search_form->getData();
$em->getRepository(Product::class)->ListAll($data);
我也认为我们可以使用数据转换器,但我不知道如何做到这一点