2012-03-28 54 views
17

使用Symfony2的entity field type一個應該指定property選項:Symfony2實體字段類型替代「屬性」或「__toString()」?

$builder->add('customers', 'entity', array(
    'multiple' => true, 
    'class' => 'AcmeHelloBundle:Customer', 
    'property' => 'first', 
)); 

但有時這是不夠的:想想兩個客戶具有相同的名稱,所以顯示電子郵件(獨特)將是強制性的。

另一種可能性是實施__toString()到模型:

class Customer 
{ 
    public $first, $last, $email; 

    public function __toString() 
    { 
     return sprintf('%s %s (%s)', $this->first, $this->last, $this->email); 
    } 
} 

後者的disadvances是你被迫顯示實體所有的形式以同樣的方式

還有其他方法可以使這更靈活嗎?我的意思是這樣一個回調函數:

$builder->add('customers', 'entity', array(
    'multiple' => true, 
    'class' => 'AcmeHelloBundle:Customer', 
    'property' => function($data) { 
     return sprintf('%s %s (%s)', $data->first, $data->last, $data->email); 
    }, 
)); 
+0

我有此相同的情況,並計劃張貼在這麼快的一個問題...我期待回答。 – Icode4food 2012-03-28 22:44:43

回答

40

我發現這真的有幫助的,我咬咬牙一個非常簡單的方式與您的代碼,這樣做,所以這裏是解決方案

$builder->add('customers', 'entity', array(
'multiple' => true, 
'class' => 'AcmeHelloBundle:Customer', 
'property' => 'label', 
)); 

而且在類客戶(實體)

public function getLabel() 
{ 
    return $this->lastname .', '. $this->firstname .' ('. $this->email .')'; 
} 

eh voila:D屬性從實體中獲取它的字符串而不是數據庫。

+6

您應該使用getters並且不直接訪問值。 'return $ this-> getLastname()。','。 $ this-> getFirstname()。' ('。$ this-> getEmail()'')';' – 2013-05-03 11:18:37

+0

這很好,除非你需要生成縮略圖或者你無法從模型中做的事情...... – darkbluesun 2015-07-17 05:10:09

1

看來這可能是由後ObjectChoiceList.phpelseif ($this->labelPath)塊添加以下塊實現的。

elseif (is_callable($this->labelPath)) { 
    $labels[$i] = call_user_func($this->labelPath, $choice); 
} 

雖然沒有嘗試過:)。

+1

這看起來確實可行,但需要黑客Symfony。如果可能,我寧願避免這種情況。當然有一個「正確」的方法來做到這一點。在我看來,這是一個相當重要的問題。 – Icode4food 2012-03-29 12:14:59

+0

@ Icode4food同意。 – gremo 2012-03-29 14:12:38

+0

那麼這是AFIK的唯一途徑。爲了使它成爲Symfony2核心,PR需要發送給github。如果我有空閒時間,我可以提交適當的單元測試。如果任何人提交的PR也很好。 – 2012-03-29 14:47:28