2012-07-31 70 views
0

我決定徹底改寫我的問題。希望我的問題更清楚這種方式。Symfony2.1嵌入式表格和外鍵關係

如何在實體中嵌入表示外鍵字段的表單?例如,一個Property擁有一個狀態表的外鍵(擁有,可用,出售等)。使用嵌入式表單,我不確定如何讓我的嵌入式表單(在這種情況下狀態)瞭解什麼父實體嵌入它,以便表單提交時,創建/更改屬性上的狀態只會改變外鍵關係。我可以通過調用$ property-> setStatus($ status)來查詢屬性並更改其狀態,所以我相信我的學說關係是正確的。

現在,我試圖改變形式的狀態時收到此錯誤提交:

Catchable Fatal Error: Object of class Test\Bundle\SystemBundle\Entity\Status could not be converted to string in /home/vagrant/projects/test.dev/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php line 1118 

我的表單創建:

$form = $this->createForm(new PropertyType(), $property); 

財產的我的屬性實體的實體關係到狀態:

/** 
* @var Status $status 
* 
* @ORM\ManyToOne(targetEntity="Test\Bundle\SystemBundle\Entity\Status") 
* @ORM\JoinColumn(name="StatusId", referencedColumnName="Id", nullable=false) 
*/ 
protected $status; 

這是我的PropertyType類中嵌入StatusType類:

->add('status', new StatusType()) 

這裏是我的StatusType表單類:

class StatusType extends AbstractType 
{ 
public $statusType = null; 

public function __construct($statusType) 
{ 
    $this->statusType = $statusType; 
} 

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 

    $builder->add('name', 'entity', array('label' => 'Status Name', 
      'class'  => 'Test\Bundle\SystemBundle\Entity\Status', 
      'property' => 'name')); 

} 

public function getParent() 
{ 
    return 'form'; 
} 

public function getDefaultOptions(array $options) 
{ 
    return array('data_class' => 'Test\Bundle\SystemBundle\Entity\Status'); 
} 

public function getName() 
{ 
    return 'status'; 
} 
} 

回答

1

沒有看到你的Status實體,這聽起來像你需要一個__toString()方法添加到它。爲了使Symfony將實體呈現爲文本,它需要知道要顯示的內容。像這樣的東西...

class Status 
{  
    public $title; 

    public function __toString() 
    { 
     return $this->title; 
    } 
} 
+0

我在我的狀態實體中有一個toString方法。該問題未顯示選擇列表,它使symfony發現StatusType類與PropertyType有關係。選擇框顯示所有狀態,但不會根據Property中的鍵預先選擇值,並且當我提交具有不同狀態的表單時,它會嘗試更新狀態記錄而不是關係。我已更新我的代碼以顯示Property to Status關係以及我如何創建表單。 – mhoff 2012-08-02 12:16:22

0

我發現的一個解決方案是將所有的邏輯放在PropertyType的狀態。

->add('status', 'entity', 
      array('class' => 'Test\Bundle\SystemBundle\Entity\Status', 
       'property' => 'name', 
       'query_builder' => function(EntityRepository $er){ 
        return $er->createQueryBuilder('status') 
        ->orderBy('status.name', 'ASC'); 
       })) 

而是嵌入StatusType的:

->add('status', new StatusType()) 

我不喜歡這種方法,因爲它使用狀態每個實體都會有這樣的重複,但它的工作暫時直到我弄清楚如何讓它工作。