Home > Software engineering >  Symfony 6 Entitytype field fetch data from database
Symfony 6 Entitytype field fetch data from database

Time:11-03

I have a submit form using EntityType from another entity class, the two entities don't have any relation between them. In my form class this is the field

->add('user', EntityType::class, [
'class'=>User::class,
'query_builder' => function(UserRepository $userRepository){
$db = $userRepository->createQueryBuilder('u');
$db->andWhere($db->expr()->isNotNull('u.name')); // get users with name
return $db;
},
'choice_label' => 'name',
'choice_value' => 'pin',
'placeholder' => 'Choose owner',
])

When submitting, i get only the pin from the user object, and store it in the database. Now i want to make edit page, where i use this "pin" value to retrieve the name of the user

When i try to load the object into the form and render it, the selected value is the placeholder default value not the actual value from the database.

CodePudding user response:

For everyone trying to reuse form with dropdown menu from another table without relations in symfony6

public function buildForm(FormBuilderInterface $builder, array $options): void
{
  $builder
     ->add('pin', ChoiceType::class, [
                'choices'=> $this->getUsers(),
    ])
}
public function getUsers(){
 $conn = $this->getEntityManager()->getConnection();
 $query = "SELECT `name`, `pin` FROM `user` where `name` is not null order by `name`  ";
 $stmt = $conn->executeQuery($query);
 return $stmt->fetchAllKeyValue(); 
 }
  • Related