This bundle provides a simple way to translate Doctrine entities in Symfony applications.
composer require symfonycasts/object-translation-bundleNote
This step is not required if you are using Symfony Flex.
return [
// ...
ObjectTranslationBundle::class => ['all' => true],
];Note
This step is not required if you are using Symfony Flex.
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use SymfonyCasts\ObjectTranslationBundle\Model\Translation as BaseTranslation;
#[ORM\Entity]
class Translation extends BaseTranslation
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
public int $id;
}Note
This step is not required if you are using Symfony Flex.
symfonycasts_object_translation:
translation_class: App\Entity\Translationsymfony console make:migration
symfony console doctrine:migrations:migrateTo mark an entity as translatable, use the Translatable attribute on the entity class
and the TranslatableProperty attribute on the fields you want to translate.
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use SymfonyCasts\ObjectTranslationBundle\Mapping\Translatable;
use SymfonyCasts\ObjectTranslationBundle\Mapping\TranslatableProperty;
#[ORM\Entity]
#[Translatable('product')]
class Product
{
// ...
#[ORM\Column(type: 'string', length: 255)]
#[TranslatableProperty]
public string $name;
#[ORM\Column(type: 'text')]
#[TranslatableProperty]
public string $description;
}You can inject the ObjectTranslator service to translate entities.
use SymfonyCasts\ObjectTranslationBundle\ObjectTranslator;
class ProductController
{
public function show(Product $product, ObjectTranslator $objectTranslator)
{
// translate into the current request locale
$translatedProduct = $objectTranslator->translate($product);
$translatedProduct->getName(); // returns the translated name (if available)
$translatedProduct->getDescription(); // returns the translated description (if available)
// ...
}
}The second argument of the translate() method allows you to specify a locale:
$product = $objectTranslator->translate($product, 'fr'); // translates into FrenchIf using Twig, you can use the translate_object filter to translate entities directly in templates.
{% set translatedProduct = product|translate_object %} {# translates into the current request locale #}
{% set frenchProduct = product|translate_object('fr') %} {# translates into French #}The Translation database table has the following structure:
id: Primary key (added by you)object_type: The alias defined in theTranslatableattribute (e.g.,product)object_id: The ID of the translated entitylocale: The locale of the translation (e.g.,fr)field: The entity property name being translated (e.g.,description)value: The translated value
Each row represents a single property translation for a specific entity in a specific locale.
You can manage these translations yourself but two console commands are provided to help:
This command exports all entity translations, in your default locale, to a CSV file.
symfony console object-translation:export translations.csvThis will create a translations.csv file at the root of your project with the following structure:
type,id,field,valueYou can then take this file to translation service for translation. Be sure to keep
the type, id, and field columns intact. The value column is what needs to be translated
into the desired language.
This command imports translations from a CSV file created by the export command after
the value column has been translated.
symfony console object-translation:import translations_fr.csv frThe first argument is the path to the CSV file, and the second argument is the locale of the translations in that file.
If you want to build a custom administration interface for managing translations in your
application (e.g. using Symfony UX, React or plain PHP), the bundle provides a
TranslationManager service. It allows you to access translations programmatically without
needing to interact directly with the database or internal services.
You can inject TranslationManager to perform CRUD operations, retrieve translation status,
or invalidate the cache.
use SymfonyCasts\ObjectTranslationBundle\TranslationManager;
class TranslationAdminController
{
public function edit(Product $product, TranslationManager $translationManager)
{
// Save a translation for a specific field and locale
$translationManager->saveTranslation($product, 'sk', 'name', 'Názov produktu');
// Save multiple translations at once
$translationManager->saveTranslationsFor($product, 'sk', [
'name' => 'Názov produktu',
'description' => 'Dlhý popis produktu...',
]);
// Get all saved translations for a given entity and locale: ['name' => '...', ...]
$translations = $translationManager->findTranslationsFor($product, 'sk');
// Get translation status (which fields are filled and which are missing)
$status = $translationManager->translationStatusFor($product, 'sk');
$status->completionRatio(); // e.g. 0.85
$status->missingFields; // list of fields that are not yet translated
// Manually invalidate cache for this entity
$translationManager->invalidateCacheFor($product);
}
}For automatic discovery of translatable entities, you can use:
// Get list of all classes marked with #[Translatable] attribute: list<TranslatableTypeInfo>
$types = $translationManager->translatableTypes();
// Get fields for a specific class or object
$fields = $translationManager->translatableFieldsFor(Product::class);For performance, translations are cached. By default, they use your cache.app pool
and have no expiration time. This can be configured:
symfonycasts_object_translation:
cache:
pool: 'cache.object_translation' # a custom pool name
ttl: 3600 # expire after one hourIf your cache pool supports cache tagging, tags are added to the cache keys. Three tags are added:
object-translation: All translations are tagged with this key.object-translation-{type}: Where{type}is the translatable alias (e.g.,product).object-translation-{type}-{id}: Where{id}is the object's identifier.
You can invalidate these tags by using the cache:pool:invalidate-tags command:
# invalidate all object translation caches
symfony console cache:pool:invalidate-tags object-translation
# invalidate only the translation cache for "product" entities
symfony console cache:pool:invalidate-tags object-translation-product
# invalidate only the translation cache for product 42
symfony console cache:pool:invalidate-tags object-translation-product-42Translations saved or deleted with TranslationManager or the object-translation:import
command are removed from the cache automatically, whether or not your pool supports tags.
Without tags, TranslationManager::invalidateCacheFor() called without a locale
clears the cache for each of your app's enabled locales.
This command preloads all translations into the cache for all your app's enabled locales.
symfony console object-translation:warmupsymfonycasts_object_translation:
# The class name of your translation entity.
translation_class: ~ # Required, Example: App\Entity\Translation
# Cache settings for object translations.
cache:
enabled: true
# The cache pool to use for storing object translations.
pool: cache.app
# The time-to-livefor cached translations, in seconds, null for no expiration.
ttl: nullIf you discover a security vulnerability, please do not open a public issue or pull request. Instead, please review this repository's Security Policy for instructions on how to report it responsibly.