Get locale from beforeUpdate lifecycle hook

Hi!.

I`m trying to make a field renaming when creating/updating a new entity, if there is another entity with same locale and same value (I’m trying to do that because there is no unique field by locale validation by default).

It works perfectly when creating (using beforeCreate hook) a new entity, because I can access to the current locale in event.params.data, then make an api call recovering the other entities by locale and check it. But beforeUpdate hook doesn`t have the current entity locale value into event.params.data.

[This is my code]

module.exports = {
  async beforeCreate(event) {
    console.log(event.params.data);
    const locale = event.params.data.locale;
    await renameSlugIfNeeded(event, locale);
  },
  async beforeUpdate(event) {
    console.log(event.params.data);
    const locale = event.params.data.locale;
    await renameSlugIfNeeded(event, locale);
  },
};

[This is my log on beforeCreate hook]

...
{
  locale: 'en',
  localizations: [],
  publishedAt: null,
  position: 5,
  slug: 'test',
  title: 'test',
  createdBy: 1,
  updatedBy: 1,
  content: [],
  createdAt: 2022-04-26T09:30:14.446Z,
  updatedAt: 2022-04-26T09:30:14.446Z
}
...

[This is my log on beforeUpdate hook]

...
{
  title: 'test',
  slug: 'test-1',
  position: 5,
  updatedBy: 1,
  content: [],
  updatedAt: 2022-04-26T09:31:22.470Z
}
...

¿How can I get the entity locale on beforeUpdate hook?, thanks! :slight_smile:

System Information
  • Strapi Version: 4.1.7:
  • Operating System: Ubuntu:
  • Database: Mysql:
  • Node Version: 16:

1 Like

Hi!.

I finally found a workaround. I can get the id of the entity I`m editing, and query its locale:

module.exports = {
  async beforeCreate(event) {
    const locale = event.params.data.locale;
    await renameSlugIfNeeded(event, locale);
  },
  async beforeUpdate(event) {
    const id = event.params.where.id;
    const locale = await getBeforeUpdateLocale(id);

    if (locale !== null) {
      await renameSlugIfNeeded(event, locale);
    }
  },
};

async function getBeforeUpdateLocale(id) {
  const page = await strapi.service('api::page.page').findOne(id);

  if (page === null) {
    return null;
  }

  return page.locale;
}
2 Likes

@aique - thanks for the workaround.

I’d also be curious to know why locale isn’t available in the beforeUpdate lifecycle event.

Would be great to get the locale instead of fetching the entity every time…