function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
dev perdev per 

Creating a Dynamic HTML table in Apex class

Hi,

Can anyone please provide me a sample code to define a method in an apex class , that would take input parameters for header of a table, list of records to display in the rows and styling for the table itslef. Basically this method should output HTML string which will be rendered in VF. 

The table has to be dynamic, meaning that depending on the header values provided, it should be able to spit out corresponding HTML table string. so if there are 3 headers provided then the table should only show three columns.

Can anyone please help with a sample code for this. Thanks!
Best Answer chosen by dev per
Deepak GulianDeepak Gulian
public static string getTableBody(List<Lead> myList){

    String htmlBody = '';

    //open table..
    htmlBody = '<table border="1" style="border-collapse: collapse"><caption>Request Summary Data</caption><tr><th>Name</th><th>Phone</th></tr>';

    //iterate over list and output columns/data into table rows...
    for(Lead l : myList){

        String myName = l.Name; if(l.Name == null){myName = '[Not Provided]';}
        String myPhone = l.Phone; if(l.Phone == null){myPhone = '[Not Provided]';}

        htmlBody += '<tr><td>' + myName + '</td><td>' + myPhone + '</td></tr>';

    }

    //close table...
    htmlBody += '</table>';

    return htmlBody;

}
I hope this piece of code help you out!

All Answers

R Z KhanR Z Khan
Seems like you need to use feilds set in SFDC to control the number of the columns. You can always pass {!STYLENAME} to yor styles. the name you can change to any saved CSS class name depeding on your logic. By list of recrods use <apex:repeat values="{!YOUR_VARIABLES_FROM_CONTROLLER}"

Mark as answered if oyu dont have anymore questiosn
Deepak GulianDeepak Gulian
public static string getTableBody(List<Lead> myList){

    String htmlBody = '';

    //open table..
    htmlBody = '<table border="1" style="border-collapse: collapse"><caption>Request Summary Data</caption><tr><th>Name</th><th>Phone</th></tr>';

    //iterate over list and output columns/data into table rows...
    for(Lead l : myList){

        String myName = l.Name; if(l.Name == null){myName = '[Not Provided]';}
        String myPhone = l.Phone; if(l.Phone == null){myPhone = '[Not Provided]';}

        htmlBody += '<tr><td>' + myName + '</td><td>' + myPhone + '</td></tr>';

    }

    //close table...
    htmlBody += '</table>';

    return htmlBody;

}
I hope this piece of code help you out!
This was selected as the best answer