2013-10-26 19 views
0

我可以通過此代碼顯示錶單。如何在form_widget上使用兩個屬性

$builder->add('icon', 'entity', array(
'class' => 'UserBundle:IconPics', 
'property' => ‘label', 'expanded' => true, 'multiple' => false, 
)); 

在樹枝

{{ form_label(form.icon) }} 
{{ form_widget(form.icon) }} 

有appeares單選按鈕標記爲 'PictureA', 'PictureB', 'PictureC' ....

但我想不僅使用 '標籤' 性質也是'圖片'實體以及使 到jpg文件的鏈接。

如何通過一個form_widget使用兩個屬性?

我的代碼如下。

我有表,如

在user.php的

/** 
* @ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\IconPics", inversedBy="icon") 
* @ORM\JoinColumn(name="icon", referencedColumnName="id",nullable=true) 
*/ 
private $icon; 

在Icon.php

/** 
* @var string 
* 
* @ORM\Column(type="string") 
*/ 

private $label; 

/** 
* @var string 
* 
* @ORM\Column(type="string") 
*/ 
private $pic; 

/** * * @ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="icon") 
* @ORM\JoinColumn(name="icon", referencedColumnName="id") 
*/ 
private $icon; 

圖標表就像

|id |pic  |label 
|1 |aaa.png |pictureA 
|2 |bbb.png |pictureB 
|3 |ccc.png |PictureC 
+0

所以,基本上你的問題是...使用實體字段類型 - 如何將基礎實體的第二個屬性(除了「屬性」屬性指定的)暴露給視圖?請儘量保持您的問題更短,更一般,以便他們可以幫助其他人以及將來:) – nifr

+0

是的,正如你所說,我想使用第二個屬性,但我不知道如何才能做到這一點,在樹枝或建設者 - >添加?我會改變標題並儘量保持簡單。謝謝。 – whitebear

+0

請看我的答案 - 希望它引導你進入正確的方向:) – nifr

回答

2

這可能不是最優雅的解決方案,但它是一個快一個。正確的解決方案可能會寫一個自定義的字段類型,這將涉及到編寫大量的代碼。

有一個簡單的技巧來實現你想要的。只需添加到您的實體的方法,將被用來獲得這兩個值一次:

public function getFormViewData() 
{ 
    return $this->getLabel() . ';' . $this->getPicture(); 
} 

然後用這個方法在property屬性:

$builder->add('icon', 'entity', array(
    // ... 
    'property' => 'formViewData', 
)); 

最後用小樹枝split filter分離得到模板中的兩個值(請參閱示例)並調整您的模板(即通過重寫form_label小部件)以使用這些值而不是原始值。

{# 
    inside the overriden widget set the label correctly before rendering it 
    and extract the picture url. 
#} 

{% set label = label|split(';')|first|trans %} 
{% set picture = label|split(';')|last %} 

{{ label }} 
{{ picture }} 

想到了嗎?

+0

這是一個很好的提示,我想我可以理解這個的基本方法。不過,我正在使用form_widget(form.icon)。這樣,我想我必須訪問每個form.icon項目。我不知道如何才能訪問每個項目... – whitebear

+0

Thx nifr,我認爲我的一般問題'如何使用兩個屬性'是sloved.I爲另一個一般問題提出新的文章.http://stackoverflow.com/questions/19609624 /如何對接入每個項-的外形widgetform – whitebear

相關問題