I need help to write a method which will do some kind of string formatting. I have list of ids of an object. It may be any object.Like this:

List<Id> listContactIds = [select id from contact limit 5];

And I have a certain string format like this:

String format = "{name} belongs to {Account.Name}";

I need to call a method. Suppose the method name is formatString.

formatString(listContacts, format);

The method should be able to return list of formatted strings. We can take the exact field names enclosed in {} from the format string.

How to acheive this?

  • 2
    Could you go through your question and check it a bit? For example, the top line will throw an error on assigning List<Contact> to List<Id>. Also, you then use Account further down. In the end, the answer should be a simple regex search and using a map (which the returned object is) to find the value by sObject.get('field'). But you should also list what you've tried so far. – zdropic Oct 31 '13 at 11:48

You could use the string format(String stringToFormat, List formattingArguments) method.


String formatted = string.format('{0} belongs to {1}', new string[]{variable1, variable2});

It could be something like this:

List<Contact> listContacts = [select name,Account.Name from Contact limit 5];
list<String> formattedstrings = new list<string>();
for (Contact cont:listContacts) {
    formattedstrings.add(cont.name+' belongs to '+cont.Account.name);

This is the working code which will handle relationship fields also:

//By Using sObject List you can store records of any object
List<sObject> acc = [Select name,Account.Name,Account.Id from Contact limit 10];

//Insted of using a single string as format, I've used a list of sting where the first and last value is
// field names and the middle one is the text you want to use in formatting.
String[] fieldformat = new String[]{'Name', 'belongs to', 'Account.Name'};

//This is a method that does the formatting for you and returns you a list of formatted strings
List<String> formatString (List<sObject> objects,  List<String> format)
    List<String> formattedStrings = new List<String>();
    for(sObject obj : objects)
        String Str = ((format[0].contains('.')) ? getString(obj,format[0]) : String.valueOf(obj.get(format[0]))) + ' ' + format[1] + ' ' + ((format[2].contains('.')) ? getString(obj,format[2]): String.valueOf(obj.get(format[2])));
     return formattedStrings;
List<String> outPut = formatString(acc, fieldformat);

String getString(Sobject obj, String str){
    String objName = str.substring(0,str.indexOf('.'));
    String fieldName = str.substring(str.indexOf('.')+1,str.length());
    return String.valueOf(obj.getSObject(objName).get(fieldName));

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.