What is the best way to handle string representations and translations of numeric codes in Symfony2?
Suppose I have an entity like this:
<?php
class Message
{
const STATUS_NEW = 0;
const STATUS_SENT = 1;
const STATUS_DELIVERED = 2;
/**
* @var int
*/
private $status = self::STATUS_NEW;
public function getStatus()
{
return $this->status;
}
}
On the front-end and in the SonataAdmin backend I do not want to show numeric codes but strings. E.g 'New', 'Sent', and 'Delivered'. But I also want to be able to translate these strings (e.g. in Dutch 'Nieuw', 'Verzonden' and 'Afgeleverd').
So there are two conversion steps: first from the numeric code to a string or translation key, and then to the localised string.
Where and how do I best do these conversions? Both in the front end in my own controllers/views and in a SonataAdmin based backed?
If I were you, I would add a method to my Class Message
public function getStatusString() {
return 'message.status.'.$this->status;
}
And then, handle it in your translation file like this:
message.en.xlf
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="file.ext">
<body>
<trans-unit id="1">
<source>message.status.0</source>
<target>New</target>
</trans-unit>
<trans-unit id="2">
<source>message.status.1</source>
<target>Sent</target>
</trans-unit>
<trans-unit id="3">
<source>message.status.2</source>
<target>Delivered</target>
</trans-unit>
</body>
</file>
</xliff>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With