php - Symfony forms - EntityType choose the choices by ID of entity
sorry for the language I'm bad in English, I'm actually creating a "pokemon game" for train me on symfony, the problem context is that i want to the user to select her first Pokemon among a list of pokemon, but I want that the user can only choose among three of them.
Example : Pokemon Entity contains 10 Pokemon. And my user can only choose between the pokemon number 1, 2 or 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,
]);
}
}
By default the EntityType show all of the Pokemon, so I added the attributes 'choices' with an array with the 3 ID of the pokemon that I want to be selectable. But that's didn't work, how can I do that please ?
Answer
Solution:
According to the Symfony doc, the best solution is to use
$this->getDoctrine()->getRepository(YourEntity::class)->find($id);
It return only the object that you need without reinventing something.
Source