Php 如何知道一个选择字段在控制器内有多少项-Symfony2

Php 如何知道一个选择字段在控制器内有多少项-Symfony2,php,symfony,symfony-forms,choicefield,Php,Symfony,Symfony Forms,Choicefield,我想在创建表单后计算选项的项目数。该字段是一个简单的Symfony's choice字段,带有用于创建项的查询生成器。我怎样才能做到这一点 <?php class MyController { public function indexAction() { $form = $this->createForm(new MyFormWithChoiceFieldType()); // suppose that the field is

我想在创建表单后计算选项的项目数。该字段是一个简单的Symfony's choice字段,带有用于创建项的查询生成器。我怎样才能做到这一点

<?php

class MyController
{
    public function indexAction()
    {
        $form = $this->createForm(new MyFormWithChoiceFieldType());

        // suppose that the field is named by "countries"
        $items = count(???);
    }
}

以下是我如何处理类别的方法

请注意,我有一个CategoryRepository。您可以在FormType类和控制器的查询生成器选项中使用此存储库中的方法

我的findAllCategories()方法返回一个查询生成器对象,因此我可以在存储库中使用另一个名为countCategories()的方法,该方法返回同一查询生成器对象的标量计数

这允许我访问控制器中的count方法,并确保couting与我用于查找类别的查询生成器一致

这是一个非常简单的示例,但是如果您有更复杂的带有连接和where子句的finder方法,它会变得更有用

在我的控制器中:

<?php

use Site\FrontendBundle\Form\Type\CategoryType;

public function indexAction()
{
    $em = $this->getDoctrine()->getManager();
    $repo = $em->getRepository('SiteFrontendBundle:Category');

    $form = $this->createForm(new CategoryType());

    $count = $repo->countAllCategories();

    return $this->render('SiteFrontendBundle:Category:count.html.twig', array(
        'form' => $form->createView(),
        'count' => $count
    ));
}

如果您需要签入细枝:

form.countries.vars.choices|length

用正确的表单字段名替换
国家

你好,威廉姆斯,谢谢你的回复。我找到了一个直接访问该字段的选项列表选项的解决方案<代码>$form->get(“field\u name”)->getConfig()->getOption(“choice\u list”)->getChoices()
,但这会导致第二次访问数据库。您的解决方案还向数据库发出两个请求,但仅用于计算有多少类别可用。我会坚持你的解决方案,直到有人提出更好的方法。我仍然认为有一种优雅的方式来实现这一点。谢谢
<?php

namespace Site\FrontendBundle\Repository;

use Doctrine\ORM\EntityRepository;

class CategoryRepository extends EntityRepository
{
    public function findAllCategories()
    {
        return $this->createQueryBuilder('c')
            ->orderBy('c.lft', 'ASC')
        ;
    }

    public function countAllCategories()
    {
        return $this
            ->findAllCategories()
            ->select('COUNT(c.id)')
            ->getQuery()
            ->getSingleScalarResult()
        ;
    }
}
form.countries.vars.choices|length