Home > Mobile >  How do I add a dropdown field containing foreign keys in Symfony?
How do I add a dropdown field containing foreign keys in Symfony?

Time:05-02

I'm coding with PHP/Symfony, where I have a Budget and Income relationship.

The Income entity contains an id (integer), name (string), amount (integer) and a foreign key (pointing to the Budget entity):

// Income.php

#[ORM\ManyToOne(targetEntity: 'Budget', inversedBy: 'incomes')]
#[ORM\JoinColumn(name: 'budget_id', referencedColumnName: 'id', nullable: 'false')]
private $budget;

...

/**
* @param mixed $budget
*/
public function setBudget(Budget $budget): void
{
  $budget->addIncome($this);
  $this->budget = $budget;
}

I have created a fully working form using FormBuilderInterface with two fields (name and amount). I'm able to save and edit the created data.

My question is how do I add a foregin key dropdown field to the form (see code below) which contains the data from the Budget entity? So for example if I have created two budgets "2021" and "2022" then I would like to have those two appear in the dropdown field. I have tried the solution below, but then I get this error message: Can't get a way to read the property "budget" in class "App\Entity\Income"

class IncomeFormType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options): void
  {
    $builder
      ->add('name')
      ->add('description')
      ->add('amount')
      ->add('budget', ChoiceType::class, ['choice_filter' => 'isSelectable'])
    ;
  }

Thanks

CodePudding user response:

You need to use Entity form class instead of Choice one:

class IncomeFormType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options): void
  {
    $builder
      ->add('name')
      ->add('description')
      ->add('amount')
      ->add('budget', EntityType::class, [
        'class' => Budget::class,
        'choice_filter' => 'isSelectable',
      ])
    ;
  }

If you need to use some field to represent your entity in the list you should add choice_label option to the field relating to corresponding field in Budget class.

Also consider to use query_builder option to filter list of appropriate entities instead of using choice_filter. It will reduce memory usage and will improve performance of your app. Example of query_builder:

'query_builder' => function (EntityRepository $er) {
    return $er->createQueryBuilder('b')
        ->where('b.isSelectable = true') // if it is just field in DB or you can use any condition here
        ->orderBy('b.name', 'ASC'); // also help you ordering your entities in right order
}
  • Related