【问题标题】:Symfony forms - EntityType choose the choices by ID of entitySymfony 表单 - EntityType 通过实体 ID 选择选项
【发布时间】:2021-11-08 17:40:29
【问题描述】:

对不起,我的英语不好,我实际上是在创建一个“口袋妖怪游戏”来训练我在 symfony 上,问题上下文是我想让用户在口袋妖怪列表中选择她的第一个口袋妖怪,但我希望用户只能在其中三个中进行选择。

示例:口袋妖怪实体包含 10 个口袋妖怪。而我的用户只能在口袋妖怪编号 1、2 或 3 之间进行选择。

<?php

namespace App\Form;

use App\Entity\Pokemon;
use App\Entity\CatchPokemon;
use App\Controller\PokemonController;
use App\Repository\PokemonRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ChooseStarterType extends AbstractType{
  public function buildForm(FormBuilderInterface $builder, array $options){

    $builder
        ->add('pokemonId', EntityType::class,[
            'class' => Pokemon::class,
            'choice_label' => 'name',
            'choices' => [
                function(PokemonRepository $pokemonRepository){ $pokemonRepository->findOneBy(['id' => 1 ]); },
                function(PokemonRepository $pokemonRepository){ $pokemonRepository->findOneBy(['id' => 2 ]); },
                function(PokemonRepository $pokemonRepository){ $pokemonRepository->findOneBy(['id' => 3 ]); },
            ]
        ])
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => CatchPokemon::class,
    ]);
}
}

默认情况下,EntityType 显示所有口袋妖怪,所以我添加了属性“选择”和一个数组,其中包含我想要选择的口袋妖怪的 3 ID。但这不起作用,请问我该怎么做?

【问题讨论】:

  • 使用query_builder 选项来过滤结果集:return $er-&gt;createQueryBuilder('p')-&gt;where('p.id IN(1,2,3)')
  • 好的,谢谢,我会看到的!
  • 非常感谢您

标签: php symfony symfony-forms


【解决方案1】:

根据 Symfony doc,最好的解决方案是使用 $this-&gt;getDoctrine()-&gt;getRepository(YourEntity::class)-&gt;find($id);

它只返回您需要的对象,而无需重新发明。

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2018-10-25
    • 1970-01-01
    • 2018-03-04
    相关资源
    最近更新 更多