【问题标题】:How to show only data of specifics rows如何仅显示特定行的数据
【发布时间】:2020-10-17 20:46:30
【问题描述】:

我正在使用 Symfony 和 Twig 模板。

我制作了一个表格,其中包含属于人的信息(姓名、出生日期、城市等..)。

我想要的只是:

  • 居住在 A 市的所有人似乎都是管理 A 市的模板
  • 居住在 B 市的所有人都转到管理 B 市的模板

这是我的代码:

/**
* @Route("/infoProspect", name="user_infoProspects", methods={"GET","POST"})
*/
public function getInfo(ProspectRepository $prospectRepository,AgencyRepository $CityRepository,AgencyRepository $CityRepository  ): Response
{
    $prospect = new Prospect();
    return $this->render('user/_infoProspect.html.twig', [
            'prospects' => $prospectRepository->findOneByCity(''),
            'agency' => $AgencyRepository->findOneByCity(''),
            'city' => $cityRepository->findOneByCity('Vern'),
        ]
    );
}

AgencyRepository 包含 city_iduser_id。 因此,选择城市 A 的人的信息转到仅根据用户 ID 管理城市 A 的代理模板。

我的模板示例: 我只需要名为“Renne”的城市,而不需要名为 Vern 的城市。

如果您需要更多信息,请咨询我。谢谢。

【问题讨论】:

  • 为什么propspects和agency在存储库功能中没有“Vern”?如果存储库只返回询问的城镇,它不会解决您的问题吗?

标签: symfony doctrine twig


【解决方案1】:

为了让您的控制器知道要使用哪个城镇,您可以使用像 @Entity 这样的参数转换器。这是一些适合您情况的代码:

/**
* @Route("infoprospect/{id_city}", name="info_prospect")
* @Entity("city", expr="repository.find(id_city)") // <- here the conversion from id_city to a hydrated doctrine entity
**/
public function getInfo(City $city, ProspectRepository $prospectRepository, AgencyRepository $AgencyRepository, CityRepository $CityRepository)
{
    // then find the people related to your city
    // if you dump city here, you will see the parameter converter found the one matching city_id
    $peopleOfCity = $city->getPeople();

    // and finally pass the people and other info to your template
    return $this->render('user/_infoProspect.html.twig', [
        'prospects' => $prospectRepository->findOneByCity(''),
        'agency' => $AgencyRepository->findOneByCity(''),
        'city' => $cityRepository->findOneByCity('Vern'),
        "people" => $peopleOfCity
    ]);
}

更多关于@Entity和参数转换在这里:https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#fetch-via-an-expression

【讨论】:

  • 当我添加 {id_city} 时出现错误“@ParamConverter 注释找不到 App\Entity\User 对象”
  • 变量id_city@Route@Entity注解中必须同名,变量city@Entity注解和你的控制器中必须同名函数声明($city)。
  • 这正是我所做的,几乎是复制和粘贴。
  • 您的错误很奇怪,因为$cityCity 的一个实例,而您的错误是关于找不到User 实例。 @Entity 注释使用链接到实体类的存储库。您还必须检查 URL 的生成是否提供了有效的 city_id ;更多关于这里的信息-> symfony.com/doc/current/routing.html#generating-urls
  • 在我的用户控制器中创建模板 infoProspect 可能不是一个好主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 2020-05-03
  • 2020-10-25
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多