[英]Symfony4 Forms - EntityType with two choice_label
I'm pretty new to symfony and symfony forms.我对 symfony 和 symfony 形式很陌生。
I have a form with an EntityType, that looks like this:我有一个带有 EntityType 的表单,如下所示:
->add('customer', EntityType::class, [
'label' => 'Kunde: ',
'class' => Customer::class,
'choice_label' => 'Name',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('c')
->select('CONCAT(c.firstname, " ", c.surname) AS Name');
}
])
But I now get an Error/Warning:但我现在收到错误/警告:
Warning: spl_object_hash() expects parameter 1 to be object, string given
Customer Entity:客户实体:
/**
* @ORM\Entity(repositoryClass="App\Repository\CustomerRepository")
*/
class Customer
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="firstname", type="string", length=50, nullable=false)
*/
private $firstname;
/**
* @var string
*
* @ORM\Column(name="surname", type="string", length=50, nullable=false)
*/
private $surname;
...
Thank you very much for your time and help.非常感谢您的时间和帮助。
You could also simply use a callback for the choice_label
您也可以简单地为
choice_label
使用回调
Eg:例如:
->add('customer', EntityType::class, [
'label' => 'Kunde: ',
'class' => Customer::class,
'choice_label' => function (Customer $customer) {
return $customer->getFirstname() . ' ' . $customer->getSurname();
// or better, move this logic to Customer, and return:
// return $customer->getFullname();
},
])
Have you created a __toString()
method in your customer entity.您是否在客户实体中创建了
__toString()
方法。
/**
* toString
*
* @return string
*/
public function __toString() {
return $this->getFirstname().' '.$this->getSurname();
}
Then, something like this should be enough :然后,这样的事情应该就足够了:
->add('customer')
If customer is related to your entityType, this should be enough如果客户与您的实体类型相关,这应该就足够了
Not sure if this works with Symfony 4 but it does work with symfony 5. This is more of an extension of Yoshis' answer than a new answer.不确定这是否适用于 Symfony 4,但它适用于 symfony 5。这更像是 Yoshis 答案的扩展,而不是新答案。
If you create a getFullname()
function as suggested by Yoshi you can do the following.如果您按照 Yoshi 的建议创建
getFullname()
函数,您可以执行以下操作。
Customer.php:客户.php:
public function getFullname(): ?string {
return $this->firstname . ' ' . $this->surname;
}
Then in your form:然后以您的形式:
->add('customer', EntityType::class, [
'label' => 'Kunde: ',
'class' => Customer::class,
'choice_label' => 'fullname'
])
Adding the fullname function to the customer also allows you to use fullname within your twig files.向客户添加全名功能还允许您在树枝文件中使用全名。
eg.例如。
{{ customer.fullname }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.