Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display dynamic default value in field of Strapi collection page?

I want to display some read only URL in STRAPI collection page. let's say I am at

/admin/plugins/content-manager/collectionType/application::my-public-form.my-public-form/1

now I have one field that need to display URL like this

https://myurl/1

is there is any way to get current url i.e. /admin/plugins/content-manager/collectionType/application::my-public-form.my-public-form/1

and in field I display https://myurl/1

like image 295
DEV Avatar asked Nov 21 '25 17:11

DEV


1 Answers

This is going to be a lengthy answer, but let me try to simplify as much as possible.

Explanation:

To achieve this you need to simply create a field in the collection type and mark it as non-editable in the admin interface. This will make it a read-only property. Next, we need to override the afterFindOne from the lifecycle hooks of the model so that when it fetches the entry from the db, we can pre-populate the url for that particular entry, so that it's displayed in the read-only field in the UI.

Implementation:

Let's assume we are creating a collection-type called Student, which some basic field like first_name, last_name, dob and student_url. We are going to make the student_url field read-only in the following way:

  1. Create the collection type Student as show in the screenshot. enter image description here

  2. Visit the newly created collection-type in the content-manager, click on Create new entry button, and then click on Configure view in the right hand panel.

enter image description here

  1. Click on the small pencil icon which is besides the student_url field to open a popup, and then set the Editable property to False and click Finish.

enter image description here

  1. At this point you're almost done, the only thing left to do is set the lifecycle hook to populate the student_url field when it's fetched from the database so that it's displayed correctly in our UI. Create a lifecycles.js file in your model folder.
// src/api/student/content-types/student/lifecycles.js
module.exports = {
  afterFindOne(event) {
    const { result } = event;
    // You can easily change this line to `/admin/plugins/content-manager/collectionType/application::my-public-form.my-public-form/${result.id}` in your project. 
    if (result) result.student_url = `https://example.com/${result.id}`;
  },
};

And that's it. Now create an entry in the admin UI with the rest of editable fields and see entry being populated automatically with the student_url. Cheers!

enter image description here

like image 157
Salvino D'sa Avatar answered Nov 24 '25 09:11

Salvino D'sa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!