【问题标题】:Sort result by countries name not by countries code, Symfony2,按国家名称而不是国家代码排序结果,Symfony2,
【发布时间】:2015-02-10 15:16:48
【问题描述】:

我正在使用 knpPaginatorBundle,我想按国家 name(或如果可能的话按翻译的国家名称)而不是国家 code 对结果进行排序,因为名称根据语言环境“en、fr、de ..”进行更改。

例如 Spain 在英语中以 S 开头,在法语中是 Espagne 并以 E 开头,但是代码是“ES”,当然是不可更改的。可以这样做吗?

这是我的代码:

树枝

<li class="sort-by-country {% if pagination.isSorted('t.country') %}active{% endif %}">{{ knp_pagination_sortable(pagination, 'Country', 't.country') }}</li>

控制器:

public function listAction($page, Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $paginator  = $this->get('knp_paginator');

    $qb = $em->getRepository('ProjectTravelBundle:Travel')->getListTravelsFrontend();

    $pagination = $paginator->paginate(
        $qb,
        $request->query->get('page', $page),10);


    return $this->render('ProjectFrontendBundle:Travel:travel-list-view.html.twig',array(
        'pagination' => $pagination,
    ));
}

存储库

//getListTravelsFrontend
public function getListTravelsFrontend()
{

    $qb = $this->createQueryBuilder('t')
        ->leftJoin('t.image', 'i')
        ->addSelect('i')
        ->leftJoin('t.agence', 'a')
        ->addSelect('a')
        ->Where('t.enabled = 1');

    return $qb;

}

实体:

class Travel
{

/**
 * @ORM\Column(name="country", type="string", length=5, nullable=false)
 *
 * @Assert\Country
 */
protected $country;

这是显示国家名称的方法,我使用此扩展程序,效果很好

namespace Project\TravelBundle\Twig;

class CountryExtension extends \Twig_Extension {
public function getFilters()
{
    return array(
        new \Twig_SimpleFilter('country', array($this, 'countryFilter')),
    );
}

public function countryFilter($countryCode,$locale = "en")
{
    $c = \Symfony\Component\Intl\Intl::getRegionBundle()->getCountryNames($locale);

    return array_key_exists($countryCode, $c)
        ? $c[$countryCode]
        : $countryCode;
}

public function getName()
{
    return 'country_extension';
}
}

【问题讨论】:

  • 您的旅行舱有国家名称字段还是只有国家代码字段?
  • @DerickF ,旅行舱只有一个国家代码,可以用国家名称代替国家代码吗?

标签: php symfony doctrine-orm


【解决方案1】:

看起来您必须将国家/地区加入查询构建器。但首先您必须描述 Travel 和 Country 之间的关系(您可以在此处找到更多关于学说注释映射的信息:http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html)。设置映射后,添加到您的查询构建器:

->leftJoin('t.country', 'c')

然后在树枝上:

{{ knp_pagination_sortable(pagination, 'Country', 'c.code') }}

也许对你有帮助:Sorting joined table with KnpPaginatorBundle, Sort over ManyToOne Relationship with KnpPaginatorBundle in Symfony2

【讨论】:

  • 但是国家不是实体所以我不能做leftJoin
  • 好的,那么 t.country 列中的内容是什么?国家代码或国家名称?
  • 我认为您必须将 t.country 替换为存储国家/地区代码的内容。
  • 国家代码,格式为国家类型-&gt;add('country', 'country', ...
  • 然后呢?它不工作? KnpPaginator 不会为您生成正确的链接吗?
猜你喜欢
  • 2018-01-19
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
相关资源
最近更新 更多