Generate attached field (uid) on POST request

System Information
  • Strapi 3.3.4:
  • Ubuntu 20.04:
  • MongoDB v4.4.2:
  • Node v14.15.1:
  • NPM v6.14.8:

Hi all :wave:,

I’ve created an ‘article’ collection type with a text (title) and uid (slug) field. The uid field is attached to the title field so that every time I create an article using the Strapi admin panel, a slug gets generated. This works as expected and even adds a number if the slug already exists. Great feature!

However, generating the slug does not work when I make a POST request to the ‘articles’ endpoint. The POST request succeeds and a new article is added to the database, but the slug field remains empty. Manually adding a value to the slug field in the POST request works, but this seems redundant and also does not utilise the ‘uniqueness’ check. Is there something I’m missing here? Would love to know your ideas in getting this to work.

Any ideas or leads are greatly appreciated! Thanks

1 Like

That’s because from Strapi Admin it makes a few extra requests to the /content-manager/explorer/uid/generate route to generate the slug and another request to the /content-manager/explorer/uid/check-availability to check if it’s available. You can take a look in your browser what data it exactly sends to them and use the same services

You can find these services here:

These are accessible with: strapi.plugins['content-manager'].services.uid

1 Like

Thank you for your response, this is exactly what I needed to point me in the right direction. Awesome!

1 Like

how to generate uid from lifecycle?

From lifecycle; my api is “help”, change as needed

module.exports = {
  async beforeCreate(event) {
    const { data } = event.params;

    if (data.name) {
      // data.slug = slugify(data.name, { lower: true });
      data.slug = await strapi.plugins[
        "content-manager"
      ].services.uid.generateUIDField({
        contentTypeUID: "api::help.help",
        field: "slug",
        data,
      });
    }
  },
  async beforeUpdate(event) {
    const { data } = event.params;
    if (data.name) {
      // data.slug = slugify(data.name, { lower: true });
      data.slug = await strapi.plugins[
        "content-manager"
      ].services.uid.generateUIDField({
        contentTypeUID: "api::help.help",
        field: "slug",
        data,
      });
    }
  },
};

In case anybody is wondering how to do the same thing in Strapi v4

This is how my lifecycles file looks like:

  async beforeCreate(event) {
    event.params.data.slug = await strapi.service('plugin::content-manager.uid').generateUIDField({
      contentTypeUID: "api::category.category",
      field: "slug",
      data: event.params.data
    })
  }
}
2 Likes