[✅ Solution] How to create a table in a calculated field?

Hey guys,

I need help. I’m trying to build a table in html to display some fields of related items. I would like your help to understand if I’m on the right path? I’ve already made this table via Automation, but I want to do it directly in the calculated field so as not to consume an Automation just for that.

Have a look here:

You need to make sure to do “@All of related field with nulls” otherwise the table might display wrong if some of the related fields are empty

2 Likes

Hey @bruno.freitas ,
that looks pretty good! As you can see in the guide posted by @shir , the output of a calculation field is the last statement of the code. So instead of using console.log, you can simply put the variable containing the table HTML at the end:

var listaProdutos = @All of Descrição Produto;
var listaQuantidade = @All of Quantidade;
var html = "<table>";
html += "<thead><tr><th>Produto</th><th>Quantidade</th></tr></thead>";
html += "<tbody>";
for (var i = 0; i < listaProdutos.length; i++) {
  html += "<tr>";
  html += "<td>" + listaProdutos[i] + "</td>";
  html += "<td>" + listaQuantidade[i] + "</td>";
  html += "</tr>";
}
html += "</tbody>";
html += "</table>";

html;

:point_up:

Does putting html at the end instead of console.log(html) solve your problem?

Cheers, Ben

2 Likes

There is a slight error in the code above. Instead of:

var html = "stable>";

It should be:

var html = "<table>";
1 Like

Well spotted @Luis - we corrected the mistake.

Quick question @Ben,

In this scenario, how can I change the formatting of the numbers?

I can only see “Text formatting of result.” The “Number formatting of result” does not appear when using the code above.

Hey Luis,
you should be able to apply any formatting you like within the for loop:

var listaProdutos = @All of Descrição Produto;
var listaQuantidade = @All of Quantidade;
var html = "<table>";
html += "<thead><tr><th>Produto</th><th>Quantidade</th></tr></thead>";
html += "<tbody>";
for (var i = 0; i < listaProdutos.length; i++) {
  var quantidade = listaQuantidade[i];

  // Example: format with two decimal places and "$" currency at the end
  var quantidadeFormatted = quantidade.toFixed(2) + " $";
 
  html += "<tr>";
  html += "<td>" + listaProdutos[i] + "</td>";
  html += "<td>" + quantidadeFormatted + "</td>";
  html += "</tr>";
}
html += "</tbody>";
html += "</table>";

html;

Hope that helps!

2 Likes

Hey Ben,

That worked very well, and it pointed me in the right direction.

However, the numbers were missing the commas, so instead of using .toFixed I use:

VariableName.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })

I hope that helps the community.

3 Likes

Hey that looks even better :100:

1 Like