2017-08-10 49 views
0

我试图设置默认值上的EntityType选择这样的:如何在Symfony3 EntityType上设置默认值?

$builder 
      ->add('town', EntityType::class, array(
       'label' => "TOWN", 
       'class' => 'AppBundle:Town', 
       'choice_label' => 'name', 
       'choice_value' => 'id', 
       'attr' => array('class' => 'form-control'), 
       'placeholder' => 'CHOOSE_AN_OPTION', 
       'required' => false, 
       'data' => $this->em->getReference('AppBundle:Town', $options['attr']['town']) 
      )); 

我试图用数据选项来做到这一点。它适用于ChoiceType,但不适用于EntityType。我试图通过数据选项镇实体ID,名称整个对象

我从控制器创建表格对象:

$finder = $this->createForm(UserFinderType::class, null, 
     array('attr' => array('role' => $this->getUser()->getRole(), 
      'town'  => empty($params['town']) ? null : $townService->findOneById($params['town'])->getId()))); 

当我通过镇ID或名称没有任何反应,占位符被示出。如果我删除占位符,则选择空白选项。

当我通过整个镇的对象,返回此错误:Catchable Fatal Error: Object of class AppBundle\Entity\Town could not be converted to string

而且,如果我实现__toString方法,我得到相同的结果,我得到的ID或名字试试。

+0

https://stackoverflow.com/a/45468030/4224384 – yceruto

回答

0

你必须Town类创建__toString功能:

AppBundle\Entity\Town 

................. 

public function __toString(){ 
    return $this->name; // If you have `name` field or u can return `id` 
}