Custom Value Formatting: Difference between revisions

From 3B Knowledge
Jump to navigation Jump to search
No edit summary
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
== Intro ==
== Intro ==
3B Docs allows you to build a library of “value formatters” – these are special functions built with JavaScript that let you apply a specific formatting to a merge tag (TODO: Add reference to Field Merging) that are stored in the Value Formatter object table.
3B Docs allows you to build a library of “Value Formatters” – these are special functions built with JavaScript that let you apply a specific formatting to a [[Merge Fields and Tags|merge tag]] that are stored in the Value Formatter object table.


== Usage ==
== Usage ==




You can use value formatters in order to adjust, change, mutate and transform values returned by merge tags. Here are some examples of how you can employ the power of value formatters:


-       Depending on the currently viewing user’s browser locale settings, change a <code>#{Contact.Id:CreatedDate}</code> merge tag to return a date in dd/mm/yyyy or mm/dd/yyyy
You can use Value Formatters in order to adjust, change, mutate and transform values returned by [[Merge Fields and Tags|merge tags]]. Here are some examples of how you can employ the power of Value Formatters:
 
-       Depending on the currently viewing user’s browser locale settings, change a <code>#{Contact.Id:CreatedDate}</code> [[Merge Fields and Tags|merge tag]] to return a date in dd/mm/yyyy or mm/dd/yyyy


-       Change a decimal with higher resolution to a lower resolution (round a decimal)
-       Change a decimal with higher resolution to a lower resolution (round a decimal)


-       Conditionally display a value, for example if the currently viewing user’s browser declares their location to be outside of your country, you may want to not show the return value of the merge field.
-       Conditionally display a value, for example if the currently viewing user’s browser declares their location to be outside of your country, you may want to not show the return value of the [[Merge Fields and Tags|merge field]].


-       Translations and internationalisation – you could build maps of translations for specific strings, say if a field from salesforce returns “Hello”, you may want to transform this to “Hola”, “Здрасти“, “Pronto”, etc. again, depending on the currently viewing user’s browser locale.
-       Translations and internationalisation – you could build maps of translations for specific strings, say if a field from salesforce returns “Hello”, you may want to transform this to “Hola”, “Здрасти“, “Pronto”, etc. again, depending on the currently viewing user’s browser locale.
Line 22: Line 23:
When you have navigated to the object list view, you can click on the “New” button which will display the new record form. What is important here is that you give the Value Formatter a unique name that has no spaces or special characters. Don’t worry about enforcing this rule yourself, we have built a salesforce validation rule to make sure that the name of the Value Formatter is compliant with 3B Docs.
When you have navigated to the object list view, you can click on the “New” button which will display the new record form. What is important here is that you give the Value Formatter a unique name that has no spaces or special characters. Don’t worry about enforcing this rule yourself, we have built a salesforce validation rule to make sure that the name of the Value Formatter is compliant with 3B Docs.


To use the newly created Value Formatter with your template, you need to navigate to a Template record, load the editor, add a merge tag (TODO: Reference to Merge Tags) and click on the merge tag. From the options list, select the value formatter that you want to apply to the merge tag. The merge tag will be transformed from say <code>{Contact.Id:CreatedDate}</code>to <code>#{Contact.Id:CreatedDate>EU_Date_Format}</code> . This arrow right chevron indicates that the merge tag is to be formatted by the Value Formatter with the same name immediately after the chevron.
To use the newly created Value Formatter with your template, you need to navigate to a Template record, load the editor, add a [[Merge Fields and Tags|merge tag]] and click on the merge tag.  
[[File:Adding Value Formatter.png|thumb|Adding Value Formatter]]


(TODO: Add image of selecting a value formatter)
 
From the options list, select the value formatter that you want to apply to the [[Merge Fields and Tags|merge tag]]. The merge tag will be transformed from say <code>{Contact.Id:CreatedDate}</code>to <code>#{Contact.Id:CreatedDate>EU_Date_Format}</code> . This arrow right chevron indicates that the merge tag is to be formatted by the Value Formatter with the same name immediately after the chevron.


== Syntax ==
== Syntax ==
When you create a value formatter, you are basically creating a JavaScript function that accepts a single parameter “value”. This JavaScript function has access to the global context and thus to the user’s navigator object, the application variables & collections and much more. This parameter “value” is the value returned by the merge tag embedded on the template.
When you create a value formatter, you are basically creating a JavaScript function that accepts a single parameter “value”. This JavaScript function has access to the global context and thus to the user’s navigator object, the application variables & collections and much more. This parameter “value” is the value returned by the [[Merge Fields and Tags|merge tag]] embedded on the template.


Note: You must always return a string value – this return value will be your “transformation” of the merge tag.
Note: You must always return a string value – this return value will be your “transformation” of the [[Merge Fields and Tags|merge tag]].


== Examples ==
== Examples ==
Here are some examples to get you started with the basic syntax used by 3B Docs for value formatters:  
Here are some examples to get you started with the basic syntax used by 3B Docs for Value Formatters:  


=== Format Date Time to EU Format Date ===
=== Format Date Time to EU Format Date ===
This example is useful for formatting “CreatedDate” to a dd/mm/yyyy format. By default, salesforce returns a date-time value in the format YYYY-MM-DDTHH:MM:SS.ZZZ. This formatter will return the date-time in date only formatted to  dd/mm/yyyy:<syntaxhighlight lang="javascript" line="1">
This example is useful for formatting “CreatedDate” to a dd/mm/yyyy format. By default, salesforce returns a date-time value in the format YYYY-MM-DDTHH:MM:SS.ZZZ. This formatter will return the date-time in date only formatted to  dd/mm/yyyy:
 
Version < 1.16<syntaxhighlight lang="javascript" line="1">
value => new Date(value).toLocaleDateString(‘en-GB’);
value => new Date(value).toLocaleDateString(‘en-GB’);
</syntaxhighlight>Version > 1.16<syntaxhighlight lang="javascript" line="1">
//Option 1
(args) => args[0].toLocalDateString('en-GB')
//Option 2
(args) => {
    const value = args[0];
    const callout = args[1];
    return value..toLocalDateString('en-GB')
}
</syntaxhighlight>
</syntaxhighlight>


Line 61: Line 75:


=== API Callouts ===
=== API Callouts ===
You can use Function Expressions to do callouts, fetch data externally, load additional resources, use JavaScript Libraries such as FullCalendar (TODO: Reference), ChartsJs (TODO: Reference, JS Tables (TODO: Add reference)<syntaxhighlight line="1">
You can use Value Formatters just like [[Custom Embedded JavaScript Functions|Function Expressions]] to connect to external systems (or APEX). In the example below, we are calling the apex class b3d.StandardFunctionsRouter and its method getVersionData, the response is parsed to return an embed element with the image. This has been applied to a ContentVersion.Id field as a value formatter.<syntaxhighlight line="1">
var getJSON = function(url, callback) {
async (args) => {
    var xhr = new XMLHttpRequest();
console.log('args', args)
    xhr.open('GET', url, true);
const value = args[0];
    xhr.responseType = 'json';
const callout = args[1];
    xhr.onload = function() {
      var status = xhr.status;
try{
      if (status === 200) {
await callout({
        callback(null, xhr.response);
endp: 'getVersionData',
      } else {
contentVersionId: value
        callback(status, xhr.response);
},
      }
false,
    };
'b3d.StandardFunctionsRouter').then(response => {
    xhr.send();
console.log('callout response from function expression: ', response);
};
let type = '';
if(response.responseObject.contentVersion.FileType == 'JPEG'){
type = 'image/jpeg';
}
return `
<embed type="${type}" src="${response.responseObject.data}"></embed>
`;
});
}catch(err){
console.error(err);
}
}


//Use like that
getJSON('http://query.yourdomain.com/v1/public/yql?q=test',
function(err, data) {
  if (err !== null) {
    alert('Something went wrong: ' + err);
  } else {
    return data.query.results
  }
});
</syntaxhighlight>
</syntaxhighlight>
[[File:FullCalendarJs.png|thumb|Full Calendar JS library]]
[[Category:3B Docs Features]]
[[Category:3B Docs Features]]
[[Category:3B Docs]]

Latest revision as of 04:09, 7 June 2023

Intro

3B Docs allows you to build a library of “Value Formatters” – these are special functions built with JavaScript that let you apply a specific formatting to a merge tag that are stored in the Value Formatter object table.

Usage

You can use Value Formatters in order to adjust, change, mutate and transform values returned by merge tags. Here are some examples of how you can employ the power of Value Formatters:

-       Depending on the currently viewing user’s browser locale settings, change a #{Contact.Id:CreatedDate} merge tag to return a date in dd/mm/yyyy or mm/dd/yyyy

-       Change a decimal with higher resolution to a lower resolution (round a decimal)

-       Conditionally display a value, for example if the currently viewing user’s browser declares their location to be outside of your country, you may want to not show the return value of the merge field.

-       Translations and internationalisation – you could build maps of translations for specific strings, say if a field from salesforce returns “Hello”, you may want to transform this to “Hola”, “Здрасти“, “Pronto”, etc. again, depending on the currently viewing user’s browser locale.

-       Offset Dates/Times to the timezone of the currently viewing user’s browser reported timezone

How To

In order to add a custom value formatter, you need to create a Value Formatter record, which you can access from the 3B Docs Application (or simply search for “Value Formatters” in the app launcher drop down).

When you have navigated to the object list view, you can click on the “New” button which will display the new record form. What is important here is that you give the Value Formatter a unique name that has no spaces or special characters. Don’t worry about enforcing this rule yourself, we have built a salesforce validation rule to make sure that the name of the Value Formatter is compliant with 3B Docs.

To use the newly created Value Formatter with your template, you need to navigate to a Template record, load the editor, add a merge tag and click on the merge tag.

Adding Value Formatter


From the options list, select the value formatter that you want to apply to the merge tag. The merge tag will be transformed from say {Contact.Id:CreatedDate}to #{Contact.Id:CreatedDate>EU_Date_Format} . This arrow right chevron indicates that the merge tag is to be formatted by the Value Formatter with the same name immediately after the chevron.

Syntax

When you create a value formatter, you are basically creating a JavaScript function that accepts a single parameter “value”. This JavaScript function has access to the global context and thus to the user’s navigator object, the application variables & collections and much more. This parameter “value” is the value returned by the merge tag embedded on the template.

Note: You must always return a string value – this return value will be your “transformation” of the merge tag.

Examples

Here are some examples to get you started with the basic syntax used by 3B Docs for Value Formatters:

Format Date Time to EU Format Date

This example is useful for formatting “CreatedDate” to a dd/mm/yyyy format. By default, salesforce returns a date-time value in the format YYYY-MM-DDTHH:MM:SS.ZZZ. This formatter will return the date-time in date only formatted to  dd/mm/yyyy:

Version < 1.16

value => new Date(value).toLocaleDateString(en-GB);

Version > 1.16

//Option 1
(args) => args[0].toLocalDateString('en-GB')
//Option 2
(args) => {
    const value = args[0];
    const callout = args[1];
    return value..toLocalDateString('en-GB')
}

Tips & Tricks

Here are some tips and tricks for using Value Formatters:

Locale, Timezone & Language

Always remember that you have access to the currently viewing user’s navigator which can help you determine their locale, timezone and language. Use this in order to internationalize a template!

//Get Timezone
Intl.DateTimeFormat().resolvedOptions().timeZone;

//Get Locale/Language
navigator.language

Geolocation

You can request the currently viewing user to grant you access to their location via using the native JavaScript APIs for geolocation requesting.

//Get User Location (request it)
if (window.navigator.geolocation) {
    window.navigator.geolocation.getCurrentPosition(console.log, console.log);
}

API Callouts

You can use Value Formatters just like Function Expressions to connect to external systems (or APEX). In the example below, we are calling the apex class b3d.StandardFunctionsRouter and its method getVersionData, the response is parsed to return an embed element with the image. This has been applied to a ContentVersion.Id field as a value formatter.

async (args) => {
	console.log('args', args)
	const value = args[0];
	const callout = args[1];
	
	try{
		await callout({
			endp: 'getVersionData',
			contentVersionId: value
		},
		false, 
		'b3d.StandardFunctionsRouter').then(response => {
			console.log('callout response from function expression: ', response);
			let type = '';
			if(response.responseObject.contentVersion.FileType == 'JPEG'){
				type = 'image/jpeg';
			}
			return `
				<embed type="${type}" src="${response.responseObject.data}"></embed>
			`;
		});
	}catch(err){
		console.error(err);
	}
}
Full Calendar JS library