Create a non-editable field in Strapi

Viewed 190

I have a project that sells products.

A product can have a price and optional: new_price. I would like to be able to sort them by price/new_price combined, meaning that I would need an additional entry in the DB like "final_price". I got an idea to create a non-editable field "new_price" in Content-Type Builder/schema.json and then update that with the final price for the product on "beforeCreate" in the lifecycles.js. However, I am not sure Strapi allows that, as I haven't been able to find a resource pointing in the documentation that it can. If there is a hacky way to do it, please advise. I am open to all kinds of other suggestions on how to do this Business logic as well.

Thank you in advance.

3 Answers

There is a way in strapi to make the field non editable on UI. You can go to Content-type-builder-> Your component-> Configure the view. And click on the text field. You can just make editable field as false. Strapi view

Ok, so I found a "hacky" way to do this. I don't like it, as it is not that beautiful and sophisticated, but it does the job.

  1. In product schema.json I added a

    "final_price": {
      "type": "decimal"
    }
    
  2. In lifecycles.js, I created a new function that will calculate my final price and write it in "final_price" attribute:

    module.exports = {
      beforeCreate(event) {
        priceCalc(event);
      },
      beforeUpdate(event) {
        priceCalc(event);
      },
    };
    
    const priceCalc = (event) => {
      const { data } = event.params;
      data.final_price = data.new_price ? data.new_price : data.price;
    };
    
  3. In the admin panel, in Content-Type Builder in Product, I clicked "Configure the view" and deleted the Final Price field from Displayed Fields section. This made the field hidden, lol.

  4. Now I am sorting all products with sort: ['final_price:asc']

That is it.Hope it helps anyone!

Related