12

The Dynamically Populating Label Parameters documentation describes how you can:

Output and update labels using the format() expression function

e.g.:

{!format($Label.mySection.myLabel, v.attribute1, v.attribute2)}

But I need to build some error strings in a controller and in a helper not directly in the component markup.

I see that in the Using Custom Labels documentation a label value can be obtained in JavaScript via:

$A.get("$Label.namespace.labelName")

But is there a way to get hold of the format function? (Simply calling it gives me "format is not defined" in both controller and helper.)

7

Would prefer a platform function or a way to get to the platform function so please answer if you have a way to do that.

But for now I have added this to my helper:

format: function(string) {
    var outerArguments = arguments;
    return string.replace(/\{(\d+)\}/g, function() {
        return outerArguments[parseInt(arguments[1]) + 1];
    });
},

which is a slight tweak of the accepted answer to MessageFormat in javascript (parameters in localized UI strings) so that the substitution values don't have to be wrapped in an array.

PS

Better to use the build-in format function - see How to add dynamic variable to custom label in lightning javascript helper class.

  • 1
    I had a similar requirement and I did exactly what you have done. – Praveen Apr 20 '17 at 5:04
2

Salesforce have initially exposed the support for $A.util.format() in their documentation by mistake.

Then they later removed it from their documentation. This code will not compile from api version 40 or later.

Here is another related post

Currently recommended method seem to be to use javascript replace() function. It would be really good if Salesforce can enable this functionality natively, but for the moment we'll have to live this :(

  • Agreed; not sure it used to be documented but good that it is. – Keith C Dec 14 '17 at 13:45
  • @KeithC I just tried to use this and it seems Salesforce have removed the reference to the api in Winter 17. releasenotes.docs.salesforce.com/en-us/winter17/release-notes/…. It would be really useful to have it though :( – Ranga Dec 14 '17 at 13:55
  • Removed from the docs or removed from the code or both? – Keith C Dec 14 '17 at 14:06
  • Removed from both now. Code won't compile with A.util.format() method. So we probably need to mark this answer as not correct. Apologies, their documentation is pretty confusing. – Ranga Dec 14 '17 at 14:25
  • OK moved the accepted back again... as its your answer would you mind editing it yourself? – Keith C Dec 14 '17 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.