如何对选择类型字段使用 __toString 方法
How can I use __toString method for choice type field
根据本教程 https://symfony.com/doc/4.1/reference/forms/types/entity.html#choice-label 我正在尝试使用 toString 方法直接从实体 FieldTypes
:
加载我的下拉选项
在我的 FieldTypesRepository.php 中,我创建了函数 toString
:
public function __toString() {
return $this->FieldTypes;
}
在我的 PagesController.php 中,我在我的 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
我也试过:
$formBuilder->add('type', EntityType::class, array(
'attr' => array('class' => 'form-control select2'), 'label' => 'Type',
'class' => FieldTypes::class,
'choice_label' => function ($fieldTypes) {
return $fieldTypes->__toString();
}
));
但是我在这里收到错误消息:
Attempted to call an undefined method named "__toString" of class
"App\Entity\FieldTypes".
In my FieldTypesRepository.php I created the function toString
将此方法放在您的实体中 App\Entity\FieldTypes
而不是在您的存储库中
当您使用实体类型时,Symfony 会自动调用显示实体的 __toString() 方法。您要么需要在 FieldType 实体中实现一个函数:
public function __toString(): ?string
{
return $this->name;
}
或者您可以使用
'choice_label' => function ($fieldTypes) {
return $fieldTypes->getName();
}
在您的表单中调用另一个函数。
根据本教程 https://symfony.com/doc/4.1/reference/forms/types/entity.html#choice-label 我正在尝试使用 toString 方法直接从实体 FieldTypes
:
在我的 FieldTypesRepository.php 中,我创建了函数 toString
:
public function __toString() {
return $this->FieldTypes;
}
在我的 PagesController.php 中,我在我的 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
我也试过:
$formBuilder->add('type', EntityType::class, array(
'attr' => array('class' => 'form-control select2'), 'label' => 'Type',
'class' => FieldTypes::class,
'choice_label' => function ($fieldTypes) {
return $fieldTypes->__toString();
}
));
但是我在这里收到错误消息:
Attempted to call an undefined method named "__toString" of class "App\Entity\FieldTypes".
In my FieldTypesRepository.php I created the function toString
将此方法放在您的实体中 App\Entity\FieldTypes
而不是在您的存储库中
当您使用实体类型时,Symfony 会自动调用显示实体的 __toString() 方法。您要么需要在 FieldType 实体中实现一个函数:
public function __toString(): ?string
{
return $this->name;
}
或者您可以使用
'choice_label' => function ($fieldTypes) {
return $fieldTypes->getName();
}
在您的表单中调用另一个函数。