2017-04-17 87 views
2

請幫助,我有一個表orderstotal_price,exchange_code(它包含貨幣代碼如USD),exchange_rate(包含貨幣匯率像:1.7)。Symfony2 - 有沒有什麼辦法在實體中創建虛擬字段?

現在,我要創建一個虛擬字段'changedTotalPrice',其中將包含changedTotalPrice = exchangeRate * totalPrice。

我不想在數據庫中創建單獨的列,因爲我的數據庫表中已經有太多的列了,而我的要求是創建更多的虛擬字段。

如果您需要任何東西或不理解我的查詢,請發表評論。

+0

爲什麼不只是實現方法'public function getExchangedTotalPrice(){return $ this-> exchangeRate * $ this-> totalPrice; ''? –

+0

感謝您的回覆。那麼我可以在查詢生成器或查找函數中使用這個函數嗎?.. – Vikash

回答

1

你可以使用特定的方法來提供你需要的東西(如註釋中所述)。

public function getExchangedTotalPrice() 
{ 
    // do the maths and return the result. 

    $result = $this->exchangeRate * $this->totalPrice; 

    return $result; 
} 

有趣的是,你可以在形式或許多其他地方鉤住這個。


如果您有實例的形式,具有生成器,看起來是這樣的:

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

    //... some other builder stuff here 
    $builder->add('exchangedTotalPrice', TextType::class, [ 
     'mapped' => false,    // this will stop the setter being called on submit 
    ]); 
} 

public function configureOptions(OptionsResolver $resolver) 
{ 
    $resolver->setDefaults([ 
     'allow_extra_fields' => true,  // youll need this to allow the extra field element 
    ]); 
} 
時的symfony試圖填充表單

,它會嘗試根據字段名稱調用getter和setter。所以會依次使用上面定義的方法。


嫩枝

同樣會發生在樹枝..

{{ Orders.exchangedTotalPrice }} 

這也將呼籲新的領域,吸氣。

我沒有測試過任何這個,所以你可能需要調試。

+0

感謝您的支持。這對我的情況非常有幫助。 :) – Vikash

+0

最受歡迎,祝你好運! – DevDonkey

相關問題