Search code examples
npmcontent-management-systemstrapi

Strapi: Auto-populate the field values based on the values in other fields in a content type


Strapi Version: v4 Operating System: macOS Database: MySQL Node Version: 16.15 NPM Version: 5.8.8

I am trying to populate a field based on the value in other fields. Example: I have a content type with fields city = Mumbai and country = India, now I need a third field called market which should have the value Mumbai - India (i.e. value of city field + “-” + value of country field).

I'm relatively newer to strapi and still exploring the tool, Can someone please help me with this?


Solution

  • This is pretty simple to achieve with the help of Strapi's Model Lifecyle Hooks.

    Step 1:
    Firstly, add the city, county & market fields to your collection type via the Content-Type builder.

    Step 2:
    Now, you need to make the field read-only to make sure that nobody gets to manually populate the field via the admin UI. You can do this by visiting any entry from your collection and then clicking on the Configure the view option from the right hand pane.

    enter image description here

    Step 3:
    Next, click on the edit icon against the market field. You will be presented with a popup similar to the below screenshot. Make the field as Editable false and click on finish. Once this is done, make sure you click on the Save button shown in the top right hand side corner of the page to permanently save your changes.

    enter image description here

    Step 4:
    Next, override the beforeCreate & beforeUpdate lifecycle hooks of the model to auto-populate the market values while entries are created/updated. To do this, you'll have to create a lifecycles.js file in the following folder: ./api/[api-name]/content-types/[content-type-name]/

    Let's say your collection name is Student.

    // src/api/student/content-types/student/lifecycles.js
    
    module.exports = {
        beforeCreate(event) {
        if (event.params.data.city && event.params.data.country) {
          const { city = "", country = "" } = event.params.data;
          event.params.data.market = city + " - " + country;
        }
      },
    
      beforeUpdate(event) {
        if (event.params.data.city && event.params.data.country) {
          const { city = "", country = "" } = event.params.data;
          event.params.data.market = city + " - " + country;
        }
      },
    };
    

    Step 5:
    That's it! Restart your strapi server and try creating or updating new entries in your collection. It should automatically populate the market value based on the city & country values.