I’m working on a Symfony2 application, that I use to manage my monthly budget.
I have an entity Expense, with an amount column that is saved as a float in the db
/**
* @ORM\Table(name="expenses")
* @ORM\Entity
*/
class Expense
{
/**
* @ORM\Column(name="amount", type="float", nullable=false)
*/
private $amount;
In my listing I want to display the amount as a string, like this:
public function getAmount()
{
return '$'.number_format($this->amount, 2);
}
but when I go to my form to add a new expense, I get the following error:
Expected argument of type "numeric", "string" given
When I change the getAmount function to only return $this->amount, then I get no error.
How can I save the value of $amount as a float in the db, but display it as a string when viewing the value?
Update:
If I change the mapping to
@ORM\Column(name="amount", type="string", nullable=false)
then it works, but then my empty form gives me a value of $0,00 in the amount field, which isn’t what I want
If you want the listing to include the dollar sign then you can create another getter specifically for that purpose, eg:
Your form will use the main getter associated with the field, ie getAmount() so it will never work if you return a string when the field type is numeric of some sort (float / integer / decimal).