Symfony4 Forms - 带有两个choice_label的EntityType
I'm pretty new to symfony and symfony forms.
I have a form with an EntityType, that looks like this:
->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.
我是symfony和symfony形式的新手。 p>
我有 具有EntityType的表单,如下所示: p>
- > add('customer',EntityType :: class,[
'label'=>'Kunde :',
'class'=> Customer :: class,
'select_label'=>'Name',
'query_builder'=> function(EntityRepository $ er){
return $ er-&gt ; createQueryBuilder('c')
- > select('CONCAT(c.firstname,“”,c.surname)AS Name');
}
])
code> pre>
但我现在得到一个错误/警告: p>
警告:spl_object_hash()期望参数1为对象,给定字符串 code> p>
客户实体 strong> p >
/ **
* @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;
/ n **
* @var string
*
* @ORM \ Column(name =“surname”,type =“string”,length = 50,nullable = false)
* /
private $ surname; \ n
...
code> pre>
非常感谢您的时间和帮助。 p>
div>
You could also simply use a callback for the choice_label
E.g.:
->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
*
* @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