Vikash Sharma
Vikash Sharma

Reputation: 33

Symfony2 - Is there any way to create virtual field in entity?

Please Help, I have a table orders with total_price, exchange_code (it contains currency code like USD), exchange_rate (contains currency rate like : 1.7).

Now here I want to create a virtual field 'exchangedTotalPrice' that will contains exchangedTotalPrice = exchangeRate * totalPrice.

I don't want to create a separate column in database because I have already too much columns in my db table and My requirement is to create more virtual fields.

Please comment if you require anything or not understand my query.

Upvotes: 3

Views: 2023

Answers (1)

DevDonkey
DevDonkey

Reputation: 4880

you can use a specific method to provide what you need (as said in comments).

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

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

     return $result;
}

whats interesting is that you can then hook into this in forms, or many other places.


Form

If you have a form for instance, with a builder that looks something like this:

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
    ]);
}

when symfony tries to populate the form, it will try to call a getter and setter on it based upon the name of the field. So will in turn use your method defined above.


Twig

The same will occur in twig..

{{ Orders.exchangedTotalPrice }}

This will also call the getter on the new field.

Ive not tested any of this, so you might need to debug.

Upvotes: 3

Related Questions