phpsymfonytranslationsonata-adminsonata

Sonata Admin - how to add Translation to one field and getID of the object?


My code:

public function create($object): void
{
    /** @var CarsEvent $object */
    $carsEvent = $object;
    $em          = $this->getEntityManager($carsEvent );

    $carsEvent->addTranslation(new CarsEventTranslation());
    
    $em->persist($sportsEvent);
    $em->flush();

}

This creates a new car object and save it into my database, and that works fine, however in this part of the code I'm calling and translation function which needs to add a translation for the NAME field into my translation table for the german language

/**
 * {@inheritdoc}
 */
public function addTranslation(Translation $translation)
{

    $translation->setLocale('de');
    $translation->setField('name');
    $translation->setContent('FixedGermanName');

    $this->translations[] = $translation;

    return $this;
}

This also works but I cannot get the objectId, so my translation table in the database is not connected with the id of object that I created, I have a function

$carsEvent->getId();

but always return NULL

My question is how to get the object id so I can store that value in my database too?


Solution

  • Solution:

    /**
     * {@inheritdoc}
     */
    public function addTranslation(Translation $translation)
    {
    
        $translation->setLocale('de');
        $translation->setField('name');
        $translation->setObject($translation);
        $translation->setContent('FixedGermanName');
    
        $this->translations[] = $translation;
    
        return $this;
    }