简体   繁体   中英

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:

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

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

    $this->translations[] = $translation;

    return $this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM