Auto generate GUID for SectionId for nested Sections in schema

I have…

I’m submitting a…

  • [ ] Regression (a behavior that stopped working in a new release)
  • [ ] Bug report
  • [ ] Performance issue
  • [x ] Documentation issue or request

We have nested section and want to generate GUID for Section ID when user clicks “Add Item”. Is there way to generate this via scripts? I want to disable this field and let UI auto-generate as GUID.

Yes, you could generate this in a script, there is a “guid()” function. So just a loop

for (var item of ctx.data.array.iv) {
   if (!item.UniqueId) {
      item.UniqueId = guid();
   }
} 

Where should I put this script out of below? I wanted to generate the moment user clicks “Add item” button.

This is not possible. It would be the update and create script which is triggered whenever the content is updated over the API (or UI)

let me try to use with create and update script.

@Sebastian I tried for normal field (root field in schema) and it works fine but it does’t work for nested object (my case). I wrote code like below in Update script. can you please check if I am missing anything?

for (var item of ctx.data.Sections.iv) {
if (!item.SectionId) {
item.SectionId = guid();
replace();
}
}

You should call “replace()” only once at the end.

I have tried that as well but it doesn’t work.

What do you mean with: “It does not work”

I added one section without SectionID and I saved it but even after saving, I can’t see any value populated in SectionId field.

Updated Code :

for (var item of ctx.data.Sections.iv) {
if (!item.SectionId) {
item.SectionId = guid();
}
}

replace();

I have forgotten the problem that the script only detects changes at the root level of contents. Therefore you just have to assign the field to itself:

for (var item of ctx.data.Sections.iv) {
   if (!item.SectionId) {
     item.SectionId = guid();
   }
}
ctx.data.Sections.iv = ctx.data.Sections.iv;

replace();

IMPORTANT: Please use code blocks next time.

Sure, Awesome :slight_smile: This works
Thanks