Search code examples
strapiheadless-cms

Strapi custom controller execute from Admin UI


I'm extending a create controller for one of my models:

async create(ctx) {
    let entity;
    if (ctx.is('multipart')) {
      const { data, files } = parseMultipartData(ctx);
      entity = await strapi.services.complaint.create(data, { files });
    } else {
      entity = await strapi.services.complaint.create(ctx.request.body);
    }
    const sanitized = sanitizeEntity(entity, { model: strapi.models.complaint });
    strapi.emitToAllUsers('complaint::created', sanitized);
    return sanitized;
  },

It works fine if I do the request from Postman for example, but is it possible to do the same if the user creates the new object from the Admin UI?

When I see the console from Strapi when I send the request from Postman:

debug POST /complaints (58 ms) 200

But, if I create a new object from the admin UI I see this instead:

debug POST /content-manager/explorer/application::complaint.complaint (1017 ms) 200

Any ideas? Is it even possible? I'm using latest Strapi version (v3) Thanks


Solution

  • If you want to execute something from Admin UI, I think you might want to look at how to implement it in models using lifecycle hooks.

    https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#models

    From what I know, controller only called on API, while service are a set of reusable functions. Models are called both by API and Admin UI.

    complaint/models/complaint.js

    module.exports = {
      lifecycles: {
        afterCreate(result, data) {
           strapi.emitToAllUsers('complaint::created', result);
        }
      }
    };
    

    You can also create a function in service and call it models lifecycle hooks.