How can I use __toString method for choice type field

1.7k views Asked by At

According to this tutorial https://symfony.com/doc/4.1/reference/forms/types/entity.html#choice-label I am trying to using the toString method to load my dropdown options directly from the enity FieldTypes:

In my FieldTypesRepository.php I created the function toString:

  public function __toString() {
    return $this->FieldTypes;
  }

In my PagesController.php I am using the function in my formbuilder:

$formBuilder->add('type', EntityType::class, array(
            'attr' => array('class' => 'form-control select2'), 'label' => 'Type',
            'class' => FieldTypes::class,
            'choices' => $FieldTypes->__toString(),
          ));

Notice: Undefined variable: FieldTypes

I also tried:

  $formBuilder->add('type', EntityType::class, array(
            'attr' => array('class' => 'form-control select2'), 'label' => 'Type',
            'class' => FieldTypes::class,
            'choice_label' => function ($fieldTypes) {
              return $fieldTypes->__toString();
              }
        ));

But here I get the error message:

Attempted to call an undefined method named "__toString" of class "App\Entity\FieldTypes".

2

There are 2 answers

0
Vyctorya On BEST ANSWER

When you use an EntityType Symfony automatically calls the __toString() method of the displayed entity. You either need to implement a function in you FieldType entity:

public function __toString(): ?string
{
   return $this->name;
}

or you can use

'choice_label' => function ($fieldTypes) {
   return $fieldTypes->getName();
}

in your form to have another function called.

1
acucchieri On

In my FieldTypesRepository.php I created the function toString

Put this method in your entity App\Entity\FieldTypes not in your repository