Script Use Cases

Prev Next

This article provides use cases for Scripts in Content Types.

Debugging: Write the Context to a Field

If you want to understand your data structure and the context object, you can just write it to a string field.

ctx.data.debug.iv = JSON.stringify(ctx, null, 2);// Tell Squidex that the content should be replaced.replace(); 

Do Not Return Sensitive Information When Queried by Client

if (ctx.isClient) { // ctx Variable contains all Context informationctx.data.password.iv = '********';// Tell Squidex that the content should be replaced.replace(); }

Do Not Allow the Client to Set Fields

if (ctx.isClient && ctx.data.password.iv) {// Tell Squidex to return a 403 (Forbidden)disallow();}

Ensure Two Fields Have the Same Value

if (data.password.iv !== data.passwordConfirm.iv) {// Tell Squidex to return a 400 (Bad Request)reject('Passwords must be the same');}

Ensure Only a Specific User can Publish Content

if (ctx.operation === 'Published' && ctx.user.email !== '[email protected]') {// Reject the call if the publisher has another email address.reject('You are not allowed to publish the content');}

Compute Field From Other Values

Store in a separate field if another field has a valid value:

ctx.data.hasPassword = { iv: !!ctx.data.password.iv };// Tell Squidex that the content should be replaced.replace();

Calculate the slug for a content title automatically:

ctx.data.slug.iv = slugifx(ctx.data.title.iv);// Tell Squidex that the content should be replaced.replace();

Calculate the number of words in a Markdown field:

ctx.data.wordCount.iv = wordCount(markdown2Text(ctx.data.html.iv)));// Tell Squidex that the content should be replaced.replace();

Calculate the number of characters in an HTML field:

ctx.data.characterCount.iv = characterCount(html2Text(ctx.data.html.iv)));// Tell Squidex that the content should be replaced.replace();

Enrich Your Content with Data From External Services

We can use the getJSON function to enrich the content with data from external services. This example is a little bit more complicated than the other examples above, but let's jump into the code first.

var url = 'https://jsonplaceholder.typicode.com/todos/1';var headers = {ApiKey: 'secret'};getJSON(url, function(result) {data.title.iv = result.title;// Tell Squidex that the content should be replaced.replace();}, headers);// I am done

When we make an asynchronous call to another service or content the script engine cannot stop the script automatically. Therefore it is very important to finish the script with a call to replace(), even if we do not make a change to the content data.

Resources