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".
答案 0 :(得分:2)
当您使用EntityType时,Symfony会自动调用所显示实体的__toString()方法。您要么需要在FieldType实体中实现一个功能:
public function __toString(): ?string
{
return $this->name;
}
或者您可以使用
'choice_label' => function ($fieldTypes) {
return $fieldTypes->getName();
}
在您的表单中调用另一个函数。
答案 1 :(得分:0)
在我的FieldTypesRepository.php中,我创建了函数toString
将此方法放在您的实体App\Entity\FieldTypes
中而不是您的存储库中