php table add values if cell repeats - php

I have a wordpress loop retriving a table like this:
I want to check if the name repeats it self and if so do a sum of partial values to show the total.
On my screenshot the 1st and 3rd rows have the same "nome" so the global value should be 85, can any one tellme how to do this ?
my php :
<?php while( have_rows('wallet_repeater') ): the_row();
echo '<div class="promotoras_item_wallet"> ';
echo '<div class="promnames_wallet"> ';
// vars
$adicionados = get_sub_field('wallet_promotora');
foreach($adicionados as $post) :
$nome = simple_fields_values("pname1");
$im = simple_fields_values("ftotop");
$cp=$adicionados ;
$imatop = $im;
$data=get_sub_field('wallet_data');
$evento=get_sub_field('wallet_evento');
$obs=get_sub_field("wallet_obs");
$numeros_horas = get_sub_field("Wallet_n_horas");
$valor_horas = get_sub_field("wallet_valorh");
$evento = get_sub_field("wallet_evento");
$horarios = get_sub_field("wallet_horario");
$total_parcial = $valor_horas * $numeros_horas."€";
$ii = wp_get_attachment_image($imatop[0]);
?>
<table id="wallet_table1" width="900px" border="0" cellspacing="2" cellpadding="0">
<tbody>
<tr>
<tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';">
<td class="wallet_data_img" width="5"><div class="w_promotora_images"><?php echo wp_get_attachment_image($imatop[0]); ?></td>
<td class="wallet_data_data" width="20"><?php echo the_sub_field('wallet_data'); ?> </td>
<td class="wallet_data_nome" width="200"><?php echo $nome[0];$nomes[]=$nome[0];?></td>
<td class="wallet_data_evento" width="10"> <?php echo the_sub_field("wallet_evento"); ?></td>
<td class="wallet_data_horarios" width="10"><?php echo the_sub_field("wallet_horario"); ?></td>
<td class="wallet_data_obs" width="10"><?php echo the_sub_field("wallet_obs"); ?></td>
<td class="wallet_data_horas" width="10"><?php echo the_sub_field("Wallet_n_horas")."h"; ?></td>
<td class="wallet_data_valorh" width="5"><?php echo the_sub_field("wallet_valorh")."€"; ?></td>
<td class="wallet_data_props" width="5"><?php echo the_sub_field("wallet_props"); ?></td>
<td class="wallet_data_total" width="5">Parcial: <?php echo $total_parcial; ?> global:
</td> </tr></tbody></table>
<?php

Stuff the query data into an associative array and after that output it.
You can do it like that:
$qry = new WP_Query('post_type' => 'your_post_type', 'posts_per_page' => -1)
$arr = array();
while($qry->have_posts()) {
$qry->the_post()
$nam = //Get the name data;
$val = //Get the «global» data;
if($qry[$nam]) {
$qry[$nam]['global'] += $val;
}
else {
$qry[$nam] = array(
'foto' => //Photo data of the current post,
'name' => //Photo data of the current post,
//and so on
'global' => $val,
);
}
}
foreach($qry as $key => $data) {
//Output your table here
}

Related

only display first column?

This code shows every info from an XML. I want to only display row number one (first from/to, symbol temperature etc)
<?php
$url = ('https://www.yr.no/sted/Norge/oslo/oslo/oslo/varsel_time_for_time.xml');
$feed = simplexml_load_file($url) or die('Can not connect to server');
$result = array();
foreach ($feed->forecast->tabular->time as $content) {
array_push($result, [ "from" => (string)$content['from'],
"to" => (string)$content['to'],
'symbol' => (string)$content->symbol['name'],
'symbol-icon' => (string)$content->symbol['var'],
'temperature' => (string)$content->temperature['value'],
'windDirection' => (string)$content->windDirection['name'],
'windSpeed' => (string)$content->windSpeed['mps'],
'windType' => (string)$content->windSpeed['name'],
]);
}
?>
<button class="collapsible"><div class="tbl-content">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<?php foreach ($result as $value) { ?>
<tr>
<td>Oslo</td>
<td><?php echo date("j. M", strtotime($value['from'])); ?> kl.<?php echo date("G", strtotime($value['from'])); ?></td>
<td><img src="http://yr.github.io/weather-symbols/png/100/<?php echo $value['symbol-icon'];?>.png" /></td>
<td><?php echo $value['temperature'] ?> °C</td>
<td><?php echo $value['windType'] ?>, <?php echo $value['windSpeed'] ?> m/s fra <?php echo $value['windDirection'] ?></td>
<td>Longtherm</td>
<td>Hour</td>
</tr>
<?php } ?>
</tbody>
</table>
</div></button>
quite unexperienced, any help is greatly appreciated
Just one of the rows? Remove the foreach! Just use $result[0] in place of $value. :-)
A defined number of rows? Use a for loop:
for ($x = 0; $x < $limit; $x++) {
$value = $result[$x];
// etc
}

How to display value if query result is NULL

Excuse me,
I have source for get value from table
foreach ($hard->result() as $row) {
$ha[] = $row->bek;
}
(bek is name of column and $hard isi name of variable return query)
then I wanna write the result with lopping too.
<?php
'<tr>';
$d = 0;
$g = 0;
$s = 0;
foreach ($mon->result() as $row) {
?>
<td class="tg-yw4l"><?php echo $row->sNama;?></td>
<td class="tg-yw4l"><?php echo $norm[$d++];?></td>
<td class="tg-yw4l"><?php echo $ha[$g++];?></td>
<td class="tg-yw4l"><?php echo $urg[$s++];?></td>
<td class="tg-yw4l"></td>
</tr>
<?php
}
?>
my question is : how to give '0', when the result from db doesn't give a value (null)
Can someone help me please,,
Thanks before
You can try this
<?php
'<tr>';
$d = 0;
$g = 0;
$s = 0;
foreach ($mon->result() as $row) {
?>
<td class="tg-yw4l"><?php isset($row->sNama) ? echo $row->sNama : echo '0'; ?></td>
<td class="tg-yw4l"><?php isset($norm[$d++]) ? echo $norm[$d++] : echo '0'; ?></td>
<td class="tg-yw4l"><?php isset($ha[$g++]) ? echo $ha[$g++] : echo '0'; ?></td>
<td class="tg-yw4l"><?php isset($urg[$s++]) ? echo $urg[$s++]] : echo '0'; ?></td>
<td class="tg-yw4l"></td>
</tr>
<?php
}
?>
<?php
$res = $mon->result();
if($res && count($res)>0){
$d = 0;
$g = 0;
$s = 0;
foreach ($res as $row) { ?>
<tr>
<td class="tg-yw4l"><?php echo $row->sNama;?></td>
<td class="tg-yw4l"><?php echo $norm[$d++];?></td>
<td class="tg-yw4l"><?php echo $ha[$g++];?></td>
<td class="tg-yw4l"><?php echo $urg[$s++];?></td>
<td class="tg-yw4l"></td>
</tr>
<?php }
}
?>
thanks for all your attention to answer my case,
my problem is how to manipulate value from the table even when the value is empty
after I tried all way, I knew my case can't be fixed if I don't change my query because when I tried to loop with index 0, the result isnot still give '0'
foreach ($hard->result() as $row) {
$ha[0] = $row->bek;
}
<td class="tg-yw4l"><?php echo $ha[0];?></td>
because of that I knew, I should change my query in order if the result is empty it must give value '0'

How to Not display empty rows?

My question is:
If you look at where it would display "
<td>1ST<?php echo $first ?></td>
"
How do I ensure that if the row associate to variable '$first' or all the others if they are empty nothing shows. Also that the '1st' doesn't show?
Have tried various things I am stumped on this!
<h2><?php echo $show_title ?></h2>
<h4>Show Date: <span class="glyphicon glyphicon-time"> </span><?php echo $show_date ?></h4>
<hr>
</a>
<hr>
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT * FROM result
WHERE first IS NOT NULL";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$dog_name = $row['dog_name'];
$placement = $row['placement'];
$class_name = $row['class_name'];
$entries = $row['entries'];
$absentee = $row['absentee'];
$entries = $row['entries'];
$first = $row['first'];
$second = $row['second'];
$third = $row['third'];
$RES = $row['RES'];
$VHC = $row['VHC'];
$DCC = $row['DCC'];
$RDCC = $row['RDCC'];
$BCC = $row['BCC'];
$RBCC = $row['RBCC'];
$BOB = $row['BOB'];
$BP = $row['BP'];
$BJ = $row['BJ'];
?>
<table class="table" border="0"></div>
<tr>
<td><strong><?php echo $class_name ?></strong> - <h6>Entries: <?php echo $entries ?> Absentees: <?php echo $absentee ?></h6></td>
<td></td>
</tr>
<tr>
<td>DCC</td>
<td><?php echo $DCC ?></td>
</tr>
<tr>
<td>RDCC</td>
<td><?php echo $RDCC ?></td>
</tr>
<tr>
<td>BCC</td>
<td><?php echo $BCC ?></td>
</tr>
<tr>
<td>RBCC</td>
<td><?php echo $RBCC ?></td>
</tr>
<tr>
<td>BOB</td>
<td><?php echo $BOB ?></td>
</tr>
<tr>
<td>BP</td>
<td><?php echo $BP ?></td>
</tr>
<tr>
<td>BJ</td>
<td><?php echo $BJ ?></td>
</tr>
<tr>
<td>1ST</td>
<td><?php echo $first ?></td>
</tr>
<tr>
<td>2ND</td>
<td><?php echo $second ?></td>
</tr>
<tr>
<td>3RD</td>
<td><?php echo $third ?></td>
</tr>
<tr>
<td>RES</td>
<td><?php echo $RES ?></td>
</tr>
<tr>
<td>VHC</td>
<td><?php echo $VHC ?></td>
</tr>
</table>
You're doing well, just apply a filtering function to each row you recieve:
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT * FROM result
WHERE first IS NOT NULL";
$result = mysqli_query($connection, $query);
if (!$result) {
trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($connection), E_USER_ERROR);
} else {
// Fetch results into array
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
// If results array is not empty
if ($data) {
echo '<table class="table" border="0"></div>
<tr>
<td>
<strong><?php echo $class_name ?></strong> - <h6>Entries: <?php echo $entries ?> Absentees: <?php echo $absentee ?></h6>
</td>
<td></td>
</tr>';
// Now let's walk through every record
array_walk($data, function($dogRecord) {
// Here we apply array_filter to each dog record, so that empty values (i.e. those evaluating to false) are filtered out
$dogRecord = array_filter($dogRecord);
// Now loop throw $dogRecord to build table
$collation = [
'DCC' => 'DCC',
'RDCC' => 'RDCC',
'BCC' => 'BCC',
'RBCC' => 'RBCC',
'BOB' => 'BOB',
'BP' => 'BOB',
'BJ' => 'BOB',
'1ST' => 'first',
'2ND' => 'second',
'3RD' => 'third',
'RES' => 'RES',
'VHC' => 'RES'
];
foreach ($dogRecord as $property => $value) {
echo '<tr>
<td>'.$collation[$property].'</td>
<td>'.$value.'</td>
</tr>';
}
});
echo '</table>';
}
}
Note that instead of simple foreach loop I'm using array_walk function. This is because since you extract variables for each record, you want undeclared (i.e. unoccupied) varables every time.
What about this:
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
// Show the table-row
}
}
The following code will iterate through each row in the result (while loop) and each key => value within each row (foreach loop); it will then check if a value is not null or the key is not equal to 'first' (if statement) and echo the results in the table element. I'm not sure I fully understood your question but I hope this helps in some small way.
<table>
<?php
if($result){
while($row = mysqli_fetch_assoc($result))
foreach($row as $key => $value){
if($value != null && $key != 'first'){
echo '<tr>';
echo '<td>' . $key . '</td>';
echo '<td>' . $value . '</td>';
echo '</tr>';
}
}
}
?>
</table>

How to Show Order Details on Checkout Success Page in Opencart 2x

I am trying to show order details for successful orders on success page but unable to do so. Another answer here suggests to modify success.php and success.tpl but it's not working on Opencart 2.
What have I tried?
catalog/controller/checkout/success.php
and added new lines in the following code:
public function index() {
$this->data['order_id'] = 0; // <-- NEW LINE
$this->data['total'] = 0; // <-- NEW LINE
if (isset($this->session->data['order_id'])) {
$this->data['order_id'] = $this->session->data['order_id']; // <-- NEW LINE
$this->data['total'] = $this->cart->getTotal(); // <-- NEW LINE
$this->cart->clear();
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['guest']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
}
$this->language->load('checkout/success');
Now added the following code into success.tpl
<?php if($order_id) { ?>
<script type="text/javascript">
// Some code here
arr.push([
"create_order",
{order_id: '<?php echo $order_id; ?>', sum: '<?php echo $total; ?>'}
]);
But it doesn't show anything on success page. The above code is to show order ID and total but I want to show all details of order including name, address, products, total, shipping, etc. Just like in the order invoice.
Any help will be appreciated. Thank you
What I did on pre 2.0 versions was to actually set a new variable to the session for the order id as I found that $this->session->data['order_id'] wasn't consistent and sometimes was getting unset by the time the user reached ControllerCheckoutSuccess.
If you'd like to use this approach, edit your catalog/model/checkout/order.php file. At or about line 302 (within the addOrderHistory method) you'll see where the script checks for order status ids to determine if it should complete the order.
Within that statement, set a new session variable of your choice to the order id passed in, perhaps $this->session->data['customer_order_id'] = $order_id
Now you have a session variable that you know will remain consistent since you've created it yourself and OpenCart won't mess with it.
If you're finding that the session order id IS remaining consistent in 2.1 > then don't worry about this, just go ahead and use the default session order id variable built in.
The next step will be for you to decide how you want your invoice data loaded, via PHP or Ajax. I wouldn't recommend using Ajax as since this could be manipulated with browser developer tools and may expose other's customer's information. By using PHP and the session you eliminate this risk since a random hacker won't have access to another customer's session.
REQUIRED FOR BOTH OPTIONS BELOW:
Open catalog/controller/checkout/success.php
Right after the language file is loaded in your index method add the following:
$order_id = false;
// If NOT using the custom variable mentioned SKIP this
if (isset($this->session->data['customer_order_id'])) {
$order_id = $this->session->data['customer_order_id'];
}
If you're using the baked in session data order id, set your order id within that statement:
if (isset($this->session->data['order_id'])) {
$this->cart->clear();
$order_id = $this->session->data['order_id'];
OPTION 1:
Add receipt data to checkout/success.
Find this line:
$data['button_continue'] = $this->language->get('button_continue');
Should be around line 77-84 or thereabout.
Here you'll load up and format all your receipt info.
Open catalog/controller/account/order.php
On line 108 you'll find the info method.
Here's where the fun starts :P
Copy all the relevant info from that method into your checkout success controller just after the $data['button_continue'] = $this->language->get('button_continue'); line mentioned above.
You'll need to go through this line by line and tweak it because remember this is designed for logged in customers, so you won't want links for returns or reorders etc.
Next you're going to want to make a new template because the common/success template is generic and used all over the place.
Copy catalog/view/theme/(your theme)/template/common/success.tpl
to: catalog/view/theme/(your theme)/template/checkout/success.tpl
Open catalog/view/theme/default/template/account/order_info.tpl
The tables you'll need to add to your success template start on line 28 and extend to line 139. If you're using a different theme, you'll need to suss this out for yourself.
Don't forget to change the path to your template in your checkout/success controller to your new checkout/success tpl file.
NOTE:
It's important to remember that all this SHOULD be done in a modification package and NOT in your core files, but I don't know your situation so that's up to you to decide.
OPTION 2:
Create your own module.
In my opinion having built for this system since version 1.4 this is the best option.
Create new controller in modules, let's call it ControllerModuleReceipt:
<?php
/**
* Controller class for displaying a receipt on checkout success.
*/
class ControllerModuleReceipt extends Controller
{
/**
* Replicates the ControllerAccountOrder::info
* method for displaying order info in our
* ControllerCheckoutSuccess::index method
*
* #param int $order_id our order id
* #return mixed receipt view
*/
public function index($setting)
{
$this->load->language('account/order');
$this->load->model('account/order');
if (empty($setting['order_id'])) {
return;
}
$order_id = $setting['order_id'];
$order_info = $this->model_account_order->getOrder($order_id);
if ($order_info) {
$data['text_order_detail'] = $this->language->get('text_order_detail');
$data['text_invoice_no'] = $this->language->get('text_invoice_no');
$data['text_order_id'] = $this->language->get('text_order_id');
$data['text_date_added'] = $this->language->get('text_date_added');
$data['text_shipping_method'] = $this->language->get('text_shipping_method');
$data['text_shipping_address'] = $this->language->get('text_shipping_address');
$data['text_payment_method'] = $this->language->get('text_payment_method');
$data['text_payment_address'] = $this->language->get('text_payment_address');
$data['text_history'] = $this->language->get('text_history');
$data['text_comment'] = $this->language->get('text_comment');
$data['column_name'] = $this->language->get('column_name');
$data['column_model'] = $this->language->get('column_model');
$data['column_quantity'] = $this->language->get('column_quantity');
$data['column_price'] = $this->language->get('column_price');
$data['column_total'] = $this->language->get('column_total');
$data['column_action'] = $this->language->get('column_action');
$data['column_date_added'] = $this->language->get('column_date_added');
$data['column_status'] = $this->language->get('column_status');
$data['column_comment'] = $this->language->get('column_comment');
$data['invoice_no'] = '';
if ($order_info['invoice_no']) {
$data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
}
$data['order_id'] = $order_id;
$data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
if ($order_info['payment_address_format']) {
$format = $order_info['payment_address_format'];
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['payment_firstname'],
'lastname' => $order_info['payment_lastname'],
'company' => $order_info['payment_company'],
'address_1' => $order_info['payment_address_1'],
'address_2' => $order_info['payment_address_2'],
'city' => $order_info['payment_city'],
'postcode' => $order_info['payment_postcode'],
'zone' => $order_info['payment_zone'],
'zone_code' => $order_info['payment_zone_code'],
'country' => $order_info['payment_country']
);
$data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$data['payment_method'] = $order_info['payment_method'];
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
if ($order_info['shipping_address_format']) {
$format = $order_info['shipping_address_format'];
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['shipping_firstname'],
'lastname' => $order_info['shipping_lastname'],
'company' => $order_info['shipping_company'],
'address_1' => $order_info['shipping_address_1'],
'address_2' => $order_info['shipping_address_2'],
'city' => $order_info['shipping_city'],
'postcode' => $order_info['shipping_postcode'],
'zone' => $order_info['shipping_zone'],
'zone_code' => $order_info['shipping_zone_code'],
'country' => $order_info['shipping_country']
);
$data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$data['shipping_method'] = $order_info['shipping_method'];
$this->load->model('catalog/product');
$this->load->model('tool/upload');
// Products
$data['products'] = array();
$products = $this->model_account_order->getOrderProducts($this->request->get['order_id']);
foreach ($products as $product) {
$option_data = array();
$options = $this->model_account_order->getOrderOptions($this->request->get['order_id'], $product['order_product_id']);
foreach ($options as $option) {
$value = false;
if ($option['type'] == 'file') {
$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
if ($upload_info) {
$value = $upload_info['name'];
}
}
if (! $value) {
$value = $option['value'];
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
);
}
$product_info = $this->model_catalog_product->getProduct($product['product_id']);
$data['products'][] = array(
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'price' => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
'total' => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value'])
);
}
// Voucher
$data['vouchers'] = array();
$vouchers = $this->model_account_order->getOrderVouchers($this->request->get['order_id']);
foreach ($vouchers as $voucher) {
$data['vouchers'][] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value'])
);
}
// Totals
$data['totals'] = array();
$totals = $this->model_account_order->getOrderTotals($this->request->get['order_id']);
foreach ($totals as $total) {
$data['totals'][] = array(
'title' => $total['title'],
'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
);
}
$data['comment'] = nl2br($order_info['comment']);
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/receipt.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/module/receipt.tpl', $data);
} else {
return $this->load->view('default/template/module/receipt.tpl', $data);
}
}
}
}
TEMPLATE:
Next let's create the template in catalog/views/theme/default/module/receipt.tpl
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left" colspan="2"><?= $text_order_detail; ?></td>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left" style="width: 50%;"><?php if ($invoice_no): ?>
<b><?= $text_invoice_no; ?></b> <?= $invoice_no; ?><br />
<?php endif; ?>
<b><?= $text_order_id; ?></b> #<?= $order_id; ?><br />
<b><?= $text_date_added; ?></b> <?= $date_added; ?></td>
<td class="text-left"><?php if ($payment_method): ?>
<b><?= $text_payment_method; ?></b> <?= $payment_method; ?><br />
<?php endif; ?>
<?php if ($shipping_method): ?>
<b><?= $text_shipping_method; ?></b> <?= $shipping_method; ?>
<?php endif; ?></td>
</tr>
</tbody>
</table>
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left" style="width: 50%;"><?= $text_payment_address; ?></td>
<?php if ($shipping_address): ?>
<td class="text-left"><?= $text_shipping_address; ?></td>
<?php endif; ?>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left"><?= $payment_address; ?></td>
<?php if ($shipping_address): ?>
<td class="text-left"><?= $shipping_address; ?></td>
<?php endif; ?>
</tr>
</tbody>
</table>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?= $column_name; ?></td>
<td class="text-left"><?= $column_model; ?></td>
<td class="text-right"><?= $column_quantity; ?></td>
<td class="text-right"><?= $column_price; ?></td>
<td class="text-right"><?= $column_total; ?></td>
<?php if ($products): ?>
<td style="width: 20px;"></td>
<?php endif; ?>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td class="text-left"><?= $product['name']; ?>
<?php foreach ($product['option'] as $option): ?>
<br />
<small> - <?= $option['name']; ?>: <?= $option['value']; ?></small>
<?php endforeach; ?></td>
<td class="text-left"><?= $product['model']; ?></td>
<td class="text-right"><?= $product['quantity']; ?></td>
<td class="text-right"><?= $product['price']; ?></td>
<td class="text-right"><?= $product['total']; ?></td>
<td class="text-right" style="white-space: nowrap;"><?php if ($product['reorder']): ?>
<i class="fa fa-shopping-cart"></i>
<?php endif; ?>
<i class="fa fa-reply"></i></td>
</tr>
<?php endforeach; ?>
<?php foreach ($vouchers as $voucher): ?>
<tr>
<td class="text-left"><?= $voucher['description']; ?></td>
<td class="text-left"></td>
<td class="text-right">1</td>
<td class="text-right"><?= $voucher['amount']; ?></td>
<td class="text-right"><?= $voucher['amount']; ?></td>
<?php if ($products): ?>
<td></td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<?php foreach ($totals as $total): ?>
<tr>
<td colspan="3"></td>
<td class="text-right"><b><?= $total['title']; ?></b></td>
<td class="text-right"><?= $total['text']; ?></td>
<?php if ($products): ?>
<td></td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tfoot>
</table>
</div>
<?php if ($comment): ?>
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?= $text_comment; ?></td>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left"><?= $comment; ?></td>
</tr>
</tbody>
</table>
<?php endif; ?>
Once again, if using your own theme you'll need to adjust this.
ADD MODULE TO CHECKOUT SUCCESS
Back in the checkout success controller we need to add the module.
Find $data['content_bottom'] = $this->load->controller('common/content_bottom');
After that line add this:
$data['receipt'] = false;
if ($order_id) {
$data['receipt'] = $this->load->controller('module/receipt', array('order_id' => $order_id));
}
ADD TO SUCCESS TEMPLATE
Open catalog/view/theme/default/common/success.tpl
After <?php echo $text_message; ?> add:
<?php if ($receipt): ?>
<?= $receipt; ?>
<?php endif; ?>
And that should be it. Once again it's best to add the changes to core files via a modification, but by creating your own module it's MUCH easier to add a modification, much less to deal with.
I haven't tested the code above but it should work or have minimal errors. Feel free to post any errors and I'll be happy to help fix them.
The awesome code that Vince post works!
But I found some Errors and PHP Notices and product table was not showing up, so i did some modifications in the code and it works 100% now.
I used the OPTION 2 and Opencart 2.2 for the tests.
Here is the code:
Receipit.php in CONTROLLER/MODULE
<?php
/**
* Controller class for displaying a receipt on checkout success.
*/
class ControllerModuleReceipt extends Controller
{
/**
* Replicates the ControllerAccountOrder::info
* method for displaying order info in our
* ControllerCheckoutSuccess::index method
*
* #param int $order_id our order id
* #return mixed receipt view
*/
public function index($setting)
{
$this->load->language('account/order');
$this->load->model('account/order');
if (empty($setting['order_id'])) {
return;
}
$order_id = $setting['order_id'];
$order_info = $this->model_account_order->getOrder($order_id);
if ($order_info) {
$data['text_order_detail'] = $this->language->get('text_order_detail');
$data['text_invoice_no'] = $this->language->get('text_invoice_no');
$data['text_order_id'] = $this->language->get('text_order_id');
$data['text_date_added'] = $this->language->get('text_date_added');
$data['text_shipping_method'] = $this->language->get('text_shipping_method');
$data['text_shipping_address'] = $this->language->get('text_shipping_address');
$data['text_payment_method'] = $this->language->get('text_payment_method');
$data['text_payment_address'] = $this->language->get('text_payment_address');
$data['text_history'] = $this->language->get('text_history');
$data['text_comment'] = $this->language->get('text_comment');
$data['column_name'] = $this->language->get('column_name');
$data['column_model'] = $this->language->get('column_model');
$data['column_quantity'] = $this->language->get('column_quantity');
$data['column_price'] = $this->language->get('column_price');
$data['column_total'] = $this->language->get('column_total');
$data['column_action'] = $this->language->get('column_action');
$data['column_date_added'] = $this->language->get('column_date_added');
$data['column_status'] = $this->language->get('column_status');
$data['column_comment'] = $this->language->get('column_comment');
$data['invoice_no'] = '';
if ($order_info['invoice_no']) {
$data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
}
$data['order_id'] = $order_id;
$data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
if ($order_info['payment_address_format']) {
$format = $order_info['payment_address_format'];
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['payment_firstname'],
'lastname' => $order_info['payment_lastname'],
'company' => $order_info['payment_company'],
'address_1' => $order_info['payment_address_1'],
'address_2' => $order_info['payment_address_2'],
'city' => $order_info['payment_city'],
'postcode' => $order_info['payment_postcode'],
'zone' => $order_info['payment_zone'],
'zone_code' => $order_info['payment_zone_code'],
'country' => $order_info['payment_country']
);
$data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$data['payment_method'] = $order_info['payment_method'];
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
if ($order_info['shipping_address_format']) {
$format = $order_info['shipping_address_format'];
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['shipping_firstname'],
'lastname' => $order_info['shipping_lastname'],
'company' => $order_info['shipping_company'],
'address_1' => $order_info['shipping_address_1'],
'address_2' => $order_info['shipping_address_2'],
'city' => $order_info['shipping_city'],
'postcode' => $order_info['shipping_postcode'],
'zone' => $order_info['shipping_zone'],
'zone_code' => $order_info['shipping_zone_code'],
'country' => $order_info['shipping_country']
);
$data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$data['shipping_method'] = $order_info['shipping_method'];
$this->load->model('catalog/product');
$this->load->model('tool/upload');
// Products
$data['products'] = array();
$products = $this->model_account_order->getOrderProducts($order_id);
foreach ($products as $product) {
$option_data = array();
$options = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']);
foreach ($options as $option) {
$value = false;
if ($option['type'] == 'file') {
$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
if ($upload_info) {
$value = $upload_info['name'];
}
}
if (! $value) {
$value = $option['value'];
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
);
}
$product_info = $this->model_catalog_product->getProduct($product['product_id']);
$data['products'][] = array(
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'price' => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
'total' => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value'])
);
}
// Voucher
$data['vouchers'] = array();
$vouchers = $this->model_account_order->getOrderVouchers($order_id);
foreach ($vouchers as $voucher) {
$data['vouchers'][] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value'])
);
}
// Totals
$data['totals'] = array();
$totals = $this->model_account_order->getOrderTotals($order_id);
foreach ($totals as $total) {
$data['totals'][] = array(
'title' => $total['title'],
'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
);
}
$data['comment'] = nl2br($order_info['comment']);
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/receipt.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/module/receipt.tpl', $data);
} else {
return $this->load->view('/module/receipt.tpl', $data);
}
}
}
}
Receipit.tpl in TEMPLATES/MODULE
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left" colspan="2"><?= $text_order_detail; ?></td>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left" style="width: 50%;"><?php if ($invoice_no): ?>
<b><?= $text_invoice_no; ?></b> <?= $invoice_no; ?><br />
<?php endif; ?>
<b><?= $text_order_id; ?></b> #<?= $order_id; ?><br />
<b><?= $text_date_added; ?></b> <?= $date_added; ?></td>
<td class="text-left"><?php if ($payment_method): ?>
<b><?= $text_payment_method; ?></b> <?= $payment_method; ?><br />
<?php endif; ?>
<?php if ($shipping_method): ?>
<b><?= $text_shipping_method; ?></b> <?= $shipping_method; ?>
<?php endif; ?></td>
</tr>
</tbody>
</table>
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left" style="width: 50%;"><?= $text_payment_address; ?></td>
<?php if ($shipping_address): ?>
<td class="text-left"><?= $text_shipping_address; ?></td>
<?php endif; ?>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left"><?= $payment_address; ?></td>
<?php if ($shipping_address): ?>
<td class="text-left"><?= $shipping_address; ?></td>
<?php endif; ?>
</tr>
</tbody>
</table>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left" style="display: table-cell"><?= $column_name; ?></td>
<td class="text-left" style="display: none"><?= $column_model; ?></td>
<td class="text-right" style="display: table-cell"><?= $column_quantity; ?></td>
<td class="text-right" style="display: table-cell"><?= $column_price; ?></td>
<td class="text-right" style="display: table-cell"><?= $column_total; ?></td>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td class="text-left" style="display: table-cell"><?= $product['name']; ?>
<?php foreach ($product['option'] as $option): ?>
<br />
<small> - <?= $option['name']; ?>: <?= $option['value']; ?></small>
<?php endforeach; ?></td>
<td class="text-left" style="display: none"><?= $product['model']; ?></td>
<td class="text-right" style="display: table-cell"><?= $product['quantity']; ?></td>
<td class="text-right" style="display: table-cell"><?= $product['price']; ?></td>
<td class="text-right" style="display: table-cell"><?= $product['total']; ?></td>
</tr>
<?php endforeach; ?>
<?php foreach ($vouchers as $voucher): ?>
<tr>
<td class="text-left"><?= $voucher['description']; ?></td>
<td class="text-left"></td>
<td class="text-right">1</td>
<td class="text-right"><?= $voucher['amount']; ?></td>
<td class="text-right"><?= $voucher['amount']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<?php foreach ($totals as $total): ?>
<tr>
<td colspan="2"></td>
<td class="text-right"><b><?= $total['title']; ?></b></td>
<td class="text-right"><?= $total['text']; ?></td>
</tr>
<?php endforeach; ?>
</tfoot>
</table>
</div>
<?php if ($comment): ?>
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?= $text_comment; ?></td>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left"><?= $comment; ?></td>
</tr>
</tbody>
</table>
<?php endif; ?>
NOTE
Before entering the codes in your store, test on a backup to make sure that your store will not be impaired.
If this code has any flaws, please let me know here
Thanks!

Editable Datatables PHP MySQL jQuery

I have a table which is fed dynamically from the database, this works as it should, I've then put the datatables functionality on the top which is working well, the sorting, search, the pagination is again working as it should.
I'm now looking at being able to edit a row and update the data back into the db and refresh the table.
My table structure
<table class="table table-striped table-hover table-bordered" id="tobebookedtable">
<thead>
<tr>
<th style="display:none;">PropID</th>
<th>ProjectNo</th>
<th>Householder</th>
<th>HouseNoName</th>
<th>Street Name</th>
<th>Postcode</th>
<th>Telephone</th>
<th>EPCPlanned</th>
<th>TAM</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$planning = db::getInstance()->query('CALL sp_tobebooked()');
foreach ($planning->results() as $planning) {
?>
<td style="display:none;"><?php echo $planning->PropID; ?></td>
<td><?php echo $planning->ProjectNo; ?></td>
<td><?php echo $planning->Householder; ?></td>
<td><?php echo $planning->HouseNoName; ?></td>
<td><?php echo $planning->StreetName; ?></td>
<td><?php echo $planning->Postcode; ?></td>
<td><?php echo $planning->Telephone; ?></td>
<td><?php echo $planning->EPCPlanned; ?></td>
<td><?php echo $planning->TAM; ?></td>
</tr>
<?php }; ?>
</tbody>
</table>
The EPCPlanned is the only field I want to update.
This here is my code for the jQuery side, the edit ability works, I can click into a cell and edit the record.
<script type="text/javascript">
$(document).ready(function() {
$('#tobebookedtable').dataTable( {
//"bProcessing": true,
//"bServerSide": true,
//"bJQueryUI": true,
"bPaginate": true,
"bStateSave": true
} );
/* Init DataTables */
var oTable = $('#tobebookedtable').dataTable();
/* Apply the jEditable handlers to the table */
oTable.$('td').editable( 'tobebooked_edit.php', {
"callback": function( sValue, y ) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1] );
//window.location.reload();
},
"submitdata": function ( value, settings ) {
console.log(value);
console.log(settings);
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition( this )[2]
};
},
"height": "26px",
"width": "100%"
} );
} );
</script>
this is the tobebooked_edit.php
<?php
require 'core/init.php';
$table="temp_tobebooked";
$rawdata = $_POST;
$query = "show columns from $table";
$result= mysql_query($query) or die(mysql_error());
$fields = array();
while ( $row = mysql_fetch_assoc($result) )
{
$fieldname = $row['Field'];
array_push($fields, $fieldname);
}
$id = $rawdata['row_id'];
$value = $rawdata['value'];
$column = $rawdata['column'];
$column = $column + 1;
$fieldname = $fields[$column];
$value = utf8_decode($value);
$query = "update $table set $fieldname = '$value' where PropID = '$id'";
$result = mysql_query($query);
if (!$result) { echo "Update failed"; }
else { echo "UPD: $value"; }
?>
When it all runs and I update a record the field Updates on the screen and shows with the "UPD:" and the entered value.
But when I check my database there is no record updated. No errors show either
How can I get the data to update in my db?
First of all, I think that this
<tr>
<?php
$planning = db::getInstance()->query('CALL sp_tobebooked()');
foreach ($planning->results() as $planning) {
?>
should be
<?php
$planning = db::getInstance()->query('CALL sp_tobebooked()');
foreach ($planning->results() as $planning) {
?>
<tr>
Then, with
"row_id": this.parentNode.getAttribute('id'),
for each td element, you select the tr element and search for the id attribute, that doesn't exists
Firstly as per rsella's comment you nee to move the row inside the loop.
Secondly as suspected you are holding the ID in a hidden cell which is infact a sibling of the editable elements rather than the parent. Try changing the table structure to the following
<tbody>
<?php
$planning = db::getInstance()->query('CALL sp_tobebooked()');
foreach ($planning->results() as $planning) {
?>
<tr id="<?php echo $planning->PropID; ?>" >
<td><?php echo $planning->ProjectNo; ?></td>
<td><?php echo $planning->Householder; ?></td>
<td><?php echo $planning->HouseNoName; ?></td>
<td><?php echo $planning->StreetName; ?></td>
<td><?php echo $planning->Postcode; ?></td>
<td><?php echo $planning->Telephone; ?></td>
<td><?php echo $planning->EPCPlanned; ?></td>
<td><?php echo $planning->TAM; ?></td>
</tr>
<?php };
?>
</tbody>
This should mean that the parent has an ID and thus this.parentNode.getAttribute('id') should be able returning the required value.
As you're only editing the EPCPlanned cell then an alternative would be
<tbody>
<?php
$planning = db::getInstance()->query('CALL sp_tobebooked()');
foreach ($planning->results() as $planning) {
?>
<tr>
<td><?php echo $planning->ProjectNo; ?></td>
<td><?php echo $planning->Householder; ?></td>
<td><?php echo $planning->HouseNoName; ?></td>
<td><?php echo $planning->StreetName; ?></td>
<td><?php echo $planning->Postcode; ?></td>
<td><?php echo $planning->Telephone; ?></td>
<td id="<?php echo $planning->PropID; ?>"><?php echo $planning->EPCPlanned; ?></td>
<td><?php echo $planning->TAM; ?></td>
</tr>
<?php };
?>
</tbody>
and in your JQuery change "row_id": this.parentNode.getAttribute('id') to this.getAttribute('id')

Categories