How to create localized entries from code?

Strapi has a built in method to synchronize localizations.

strapi.plugin(‘i18n’).service(‘localizations’).syncLocalizations(entry, { model })

Here’s how to use it:

// Create your localized entries
const localizedEntities = await Promise.all(
  ['de', 'fr'].map((locale) => {
    strapi.entityService.create('api::foo.bar', { data: { ...data, locale } });
  })
);

// Create the main entry and link all of the localized entries to it
const mainEntry = await strapi.entityService.create('api::foo.bar', {
  data: {
    ...data,
    locale: 'en',
    localizations: localizedEntities.map((entry) => entry.id),
  },
  populate: ['localizations'], // localizations needs to be populated for the upcoming `syncLocalizations()` call
});

await strapi
  .plugin('i18n')
  .service('localizations')
  .syncLocalizations(mainEntry, { model: strapi.getModel('api::foo.bar') });
5 Likes