Display custom fields data in an HTML table

Today, here is a simple TXP PHP script I would like to share with you.

For my latest project I needed to display a price list in an HTML table based on corresponding articles. My articles refer to products. I use custom fields to store special descriptions informations and prices. These custom fields are named like this:

  1. Table_Line_1
  2. Table_line_2
  3. (…) and so on (…)

These simple text inputs are populated by a semi-colon separated list of information:

String 1 ; String 2 ; price 1 ; price 2 ; price 3

Into the template for my “Prices” page, I put my html markup table and use an article_custom tag to call a form named “inner_table_builder” (type misc). Following is the script to grab all the custom fields data and display it in multiple table rows.

The script

<txp:php>

/**
* @script: display each rows from the 10 custum fields article
*
* @copyright: cara-tm, http://cara-tm.com
* @licence: Creative Common 2, http://creativecommons.org/licenses/by-nc-nd/2.0/fr/deed.en_US
* @author Patrick LEFEVRE <patrick[dot]lefevre[at]gmail[dot]com>
* @version 1.03
**/

// uncomment below if u want to use local currency format for prices

//setlocale(LC_MONETARY, 'fr_FR@euro');

// grab needed global variables from core. get current article's title

global $thisarticle;
$title = $thisarticle['title'];

// loop for main table datas. Query on custom fields

for($i=1; $i<10; $i++) {
	$line = safe_rows('Title, custom_'.$i.'', 'textpattern', 'Title = "'.$title.'"');

	// avoid blank fields

	if(!empty($line[0]['custom_'.$i])) {

		// start display table inner structure

		echo '<tr class="line">';
		echo '<td class="left">'.$line[0]['Title'].'</td>';

		// place custom fields into an array

		$el = explode(";", $line[0]['custom_'.$i]);

		// display array content based on keys

		echo '<td class="center">'.$el[0].'</td>';
		echo '<td class="center">'.$el[1].'</td>';

/*
simple currency format with number_format function (prices are writting with a comma decimal value)
use instead : htmlentities(money_format('%.2n',$line3[4]),ENT_QUOTES,'ISO-8859-15')
*/
		echo '<td class="center">'.number_format(str_replace(',','.',$el[2]),2, ',', ' ').' &euro;</td>';
		echo '<td class="center">'.number_format(str_replace(',','.',$el[3]),2, ',', ' ').' &euro;</td>';
		echo '<td class="center">'.number_format(str_replace(',','.',$el[4]),2, ',', ' ').' &euro;</td>';
		echo '</tr>';
	}

}

// uncomment below if locale currency formating is used

// setlocale(LC_MONETARY, '');
</txp:php>

You’ve now got your product information displayed in an HTML table. All changes made to the custom fields are updated.

comments powered by Disqus