在PrestaShop的product.tpl中实现动态Google Chart产品价格走势图
Got it, let's transform that static price chart into a dynamic one that pulls historical price data straight from your PrestaShop database using the product ID. Here's a step-by-step solution tailored to PrestaShop's architecture:
Step 1: Fetch Price History via Controller Override
First, we'll extend the ProductController (using an override to avoid modifying core files) to fetch the product's price history and pass it to the template.
Create or edit the override file at override/controllers/front/ProductController.php:
<?php class ProductController extends ProductControllerCore { public function initContent() { parent::initContent(); // Get the current product's ID $productId = (int)$this->product->id; // Fetch historical price data from your database // Replace the table/columns with your actual price history storage (example below) $priceHistory = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT `date`, `price` FROM `'._DB_PREFIX_.'product_price_history` WHERE `id_product` = '.(int)$productId.' ORDER BY `date` ASC '); // Format data for Google Charts (convert MySQL dates to JS-compatible format) $chartData = []; foreach ($priceHistory as $entry) { $dateParts = explode('-', $entry['date']); // JS months are 0-indexed, so subtract 1 from the MySQL month value $chartData[] = [ 'new Date('.$dateParts[0].', '.((int)$dateParts[1]-1).', '.$dateParts[2].')', (float)$entry['price'] ]; } // Pass the formatted data to the Smarty template $this->context->smarty->assign([ 'price_history' => $chartData ]); } }
Notes for the Database Query:
- Replace
ps_product_price_historywith your actual table name. If you don't have a dedicated price history table, see the "Create a Price History Table" section below. - If you're tracking price changes using PrestaShop's built-in
ps_specific_pricetable, adjust the query to pull relevant data from there instead.
Step 2: Update the Product Template
Now modify your product.tpl file to replace the static data with the dynamic data from the controller.
First, add the chart container (if it's not already present):
<div id="chart_div" style="width: 100%; height: 400px;"></div>
Then update the Google Charts script to use the dynamic price_history variable:
{literal}<script type="text/javascript"> google.charts.load('current', {packages: ['corechart', 'line']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('date', 'Date'); data.addColumn('number', 'Price'); data.addRows([ {/literal} {foreach from=$price_history item=entry} [{$entry[0]}, {$entry[1]}]{if not $smarty.foreach.entry.last},{/if} {/foreach} {literal} ]); var options = { hAxis: { title: 'Date' }, vAxis: { title: 'Price' }, lineWidth: 2, pointSize: 8, }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } </script>{/literal}
Step 3: Critical Setup & Checks
Activate the Controller Override
After creating the override file, go to your PrestaShop backoffice:
- Navigate to Advanced Parameters > Performance
- Click Clear cache to enable the override.
Create a Price History Table (If Needed)
If you don't already track product price changes, create a dedicated table with this SQL query:
CREATE TABLE `ps_product_price_history` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_product` int(11) NOT NULL, `date` date NOT NULL, `price` decimal(17,2) NOT NULL, PRIMARY KEY (`id`), KEY `id_product` (`id_product`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You'll also need to add logic to insert data into this table when a product's price changes (use the actionProductUpdate hook in a custom module to automate this).
Error Handling
Add a check in the template to handle cases where there's no price history data:
{if empty($price_history)} <p>No price history available for this product.</p> {else} <!-- Chart container and script go here --> {/if}
内容的提问来源于stack exchange,提问作者Xarxou

