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

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!

Related

foreach returning Warning: Illegal string offset 'model_id'

I am trying to call the make_id from the model controller, but every time I just get illegal string, please help me with this, what I am doing wrong?
code from model :
public function getTotalModelsByMark($mark_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "models WHERE mark_id = '" . (int)$mark_id . "'");
return $query->row;
}
code from controller :
$this->load->model('catalog/models');
$data['models'] = array();
$results = $this->model_catalog_models->getTotalModelsByMark($mark_info['mark_id']);
foreach ($results as $result) {
$data['models'][] = array(
'model_id' => $result['model_id'],
'name' => $result['name'],
'mark_id' => $result['mark_id'],
'status' => $result['status'],
'category' => $result['category'],
'edit' => $this->url->link('catalog/models/edit', 'token=' . $this->session->data['token'] . '&model_id=' . $result['model_id'] . $url, true)
);
}
code from view :
<?php if ($models) { ?>
<?php foreach ($models as $model) { ?>
<tr>
<td class="text-center"><?php if (in_array($model['model_id'], $selected)) { ?>
<input type="checkbox" name="selected[]" value="<?php echo $model['model_id']; ?>" checked="checked" />
<?php } else { ?>
<input type="checkbox" name="selected[]" value="<?php echo $model['model_id']; ?>" />
<?php } ?></td>
<td class="text-left"><?php echo $model['name']; ?></td>
<td class="text-left"><?php echo $model['mark_id']; ?></td>
<td class="text-right"><?php echo $model['status']; ?></td>
<td class="text-right"><?php echo $model['category']; ?></td>
<td class="text-right"><i class="fa fa-pencil"></i></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td class="text-center" colspan="4"><?php echo $text_no_results; ?></td>
</tr>
<?php } ?>
When don't have results I get the $text_no_results with no errors, but when I have records to show I get Illegal string offset 'model_id''name' 'mark_id' 'status' 'category,'from this morning I trying to get this fix, but I can't, this is open cart.
Try this:
public function getTotalModelsByMark($mark_id) {
$sql = "SELECT * FROM ". DB_PREFIX."models WHERE mark_id={$mark_id}";
return $this->db->query($sql)->rows();
}
And replace this:
if ($models)
to:
if (count($models)>0)

Codeigniter multiple foreach loop

I have two tables meals type and meals. I want to print each meals corresponding to its meals type.
Error is that only showing last meals type meals only
view page is like
View
<?php
foreach ($mealstype as $type) {
?>
<h2><?php echo $type->type; ?></h2>
<table class="table table-bordered">
<tr>
<th>Meals</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
foreach ($meals as $meals_get) {
?>
<tr>
<td><?php echo $meals_get->item; ?></td>
<td><?php echo $meals_get->price; ?></td>
</tr>
<?php } ?>
<tr>
<td> <input type="checkbox" class="ck" value="total"> Toal</td>
<td>2050</td>
</tr>
</tbody>
</table>
<?php
}
?>
Controller
function availability() {
$this->data['mealstype'] = $this->Home_model->mealstype();
foreach ($this->data['mealstype'] as $type) {
$typeid = $type->id;
$meals[] = $this->Home_model->meals($typeid, $hotel_id);
}
$this->data['meals'] = $meals[];
$this->load->view('home2', $this->data);
}
Please check this answer
Controller:
public function availability() {
$build_array = array();
mealstype= $this->Home_model->mealstype();
foreach($mealstype as $row){
$build_array[] = array(
'parent_array' => $row,
'child_array' =>$this->Home_model->meals($row->id,$hotel_id),
'child_sum' =>$this->Home_model->meals_sum($row->id,$hotel_id)
);
}
$this->data['build_array'] = $build_array;
}
and the view page is like this:
View:
<?php foreach($build_array as $type){?>
<h2><?php echo $type['parent_array']->type;?></h2>
<table class="table table-bordered">
<tr>
<th>Meals</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
foreach ($type["child_array"] as $meals_get) {?>
<tr>
<td><?php echo $meals_get->item;?></td>
<td><?php echo $meals_get->price;?></td>
</tr>
<?php }?>
<tr>
<td> Toal</td>
<td>2050</td>
</tr>
<?php } ?>
Controller, check "hotel_id"
function availability()
{
$this->data['mealstype'] = $this->Home_model->mealstype();
if( count( $this->data['mealstype'] ) > 0 )
{
foreach($this->data['mealstype'] as $type)
{
$type->meals = $this->Home_model->meals( $type->id, $hotel_id ); // hotel_id no declared???
}
}
$this->load->view('home2', $this->data);
}
View
<?php if( count( $mealstype ) > 0): foreach( $mealstype as $type ): ?>
<h2><?php echo $type->type; ?></h2>
<table class="table table-bordered">
<thead>
<tr>
<th>Meals</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php if( count( $type->meals ) > 0 ): foreach( $type->meals as $meals_get ): ?>
<tr>
<td><?php echo $meals_get->item; ?></td>
<td><?php echo $meals_get->price; ?></td>
</tr>
<?php endforeach; endif; ?>
<tr>
<td><input type="checkbox" class="ck" value="total"> Toal</td>
<td>2050</td>
</tr>
</tbody>
</table>
<?php endforeach; endif ?>
Try to replace into this :
function availability() {
$data = array();
$data['mealstype'] = $this->Home_model->mealstype();
foreach ($data['mealstype'] as $type) {
$typeid = $type->id;
$type->meals = $this->Home_model->meals($typeid,$hotel_id);
}
$this->load->view('home2', $data);
}
check it and print_r($data); what it comes set on the basis of that in view file..
You have $hotel_id I am not sure where you set this I can not see it any where else.
We also need to see your model
public function availability() {
$data['mealstypes'] = array();
$mealstypes = $this->home_model->mealstype();
foreach ($mealstypes as $mealstype)
{
$meals = array();
$meals_results = $this->home_model->meals($mealstype->id, $hotel_id);
foreach ($meals_results $meal_result) {
$meals[] = array(
'mealstype' => $meal_result->mealstype,
'price' => $meal_result->price
);
}
$data['mealstypes'][] = array(
'type' => $mealstype->type
'meals' => $meals
);
}
$this->load->view('someview', $data);
}
View
<?php foreach ($mealstypes as $mealstype) {?>
<h2><?php echo $mealstype['type'];?></h2>
<?php foreach ($mealstype['meals'] as $meal) {?>
<?php echo $meal['mealstype'];?>
<?php echo $meal['price'];?>
<?php }?>
<?php }?>

php table add values if cell repeats

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
}

Getting magento Attribute on item returns blank

I am trying to get some custom attributes to show in magento like Color, Delivery_Time...
I could call Some Attributes with :
<?php echo $item->getName();?>
<?php echo $item->getWeight();?>
But i could'nt call the most of the attributes. i've tried also :
<?php echo $this->htmlEscape($item->getData('luftkammern'));?>
<?php echo $item->getAttributeText('spannung'); ?>
Nothing works!!
Code of attributes :
<?php
$_helper = $this->helper('catalog/output');
$_product = $this->getProduct()
?>
<?php if($_additional = $this->getAdditionalData()): ?>
<h2><?php echo $this->__('Additional Information') ?></h2>
<table class="data-table" id="product-attribute-specs-table">
<col width="25%" />
<col />
<tbody>
<?php foreach ($_additional as $_data): ?>
<tr>
<th class="label"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data"><?php echo $_helper->productAttribute($_product,$_data['value'], $_data['code']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script type="text/javascript">decorateTable('product-attribute-specs-table')</script>
<?php endif;?>
code
echo $this->__('Additional Information');?>
<table class="data-table" id="product-attribute-specs-table">
<col width="25%" />
<col />
<tbody>
<?php foreach ($_additional as $_data): ?>
<tr>
<th class="label"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
can anyone help please ?
If you need to get those attributes in checkout page, you can do like this :
$_product = $item->getProduct();
$pid = $_product->getId();
$product = Mage::getModel('catalog/product')->load($pid);
/* getting some attributes */
$color = $product->getData('color');
$manufacturer = $product->getData('manufacturer');
$delivery_date = $product->getData('delivery_date');
....
Hope it will help you.
You can get attributes from a product by calling the correct get function.
For example to receive the color use:
echo $item->getColor();
To receive the manufacturer use:
echo $item->getManufacturer();
Also you have to make sure that your product has been fully loaded. Try this:
print_r($item->getData());
Please check the following code:
$attributes = $product->getAttributes();
$additional_data = array();
foreach ($attributes as $attribute) {
if ($attribute->getIsVisibleOnFront() && $attribute->getIsUserDefined()) {
$value = $attribute->getFrontend()->getValue($product);
if (!$product->hasData($attribute->getAttributeCode())) {
$value = Mage::helper('catalog')->__('N/A');
} elseif ((string)$value == '') {
$value = Mage::helper('catalog')->__('No');
} elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
$value = Mage::app()->getStore()->convertPrice($value, true);
}
if (is_string($value) && strlen($value)) {
$additional_data[$attribute->getAttributeCode()] = array(
'label' => $attribute->getStoreLabel(),
'value' => $value,
'code' => $attribute->getAttributeCode()
);
}
}
}
/* Your code here */
<h2><?php echo $this->__('Additional Information') ?></h2>
...
<?php foreach ($additional_data as $_data): ?>
...

Remove empty columns from table drawn using PHP

I've created a size chart using php and mysql for my website. The table is 9 columns wide, however not all columns are always used.
So far I haven't figured out a way to have it skip columns with NA for the column heading. Hoping someone can shed some light on this or point me in the right direction.
Here is the code:
if (!empty($insizes)) {
?>
<div class="ui-widget infoBoxContainer">
<div class="ui-widget-header ui-corner-top infoBoxHeading">
<span><?php $products_name = $product_info['products_name']; echo $products_name; ?> Sizing Chart</span></div>
<table border="0" cellpadding="5" cellspacing="0" id="sizeChart" bgcolor="#ffffff" width="100%">
<tbody width="90%">
<tr>
<td>Size</td>
<?php foreach ($headings as $headingo) { $heading = strtolower(str_replace(" ", "<br>", $headingo)); ?>
<td><?php echo ($product_info["$heading"]); ?></td><?php } ?>
<td>Price</td>
</tr>
<?php
foreach ($insizes as $size)
{
$sizeo = strtolower(str_replace(" ", "", $size));
$sizeo = str_replace("-", "", $sizeo);
?>
<tr>
<td> <?php echo $size; ?></td>
<?php
foreach ($measurements as $measurement) {
$measurementx = $sizeo . '_' . $measurement;
?>
<td><?php echo number_format($product_info["$measurementx"], 0, '.', ''); ?>"<br><span class="sizeChartSm">(<?php echo number_format($product_info["$measurementx"] * 2.54, 1, '.', ''); ?>cm)</span></td>
<?php
}
?>
<td>
<?php
echo $sizeprices["$size"];
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</p>
<?php
}
Thanks a bunch!
Chris
Edit: Here is the rest of the info.
/* <!--- SIZE CHART ---> */
$sizes = array('3X Small', '2X Small', 'X Small', 'Small', 'Medium', 'Large', 'X Large', '2X Large', '3X Large', '4X Large', '5X Large', 'Twin', 'Full', 'Queen', 'King', 'Standard', 'Queen Deep Pocket', 'King Deep Pocket');
$measurements = array('waistmin', 'waistmax', 'legmin', 'legmax', 'crotchwidth', 'maxhip', 'height');
$headings = array ('heading_1', 'heading_2', 'heading_3', 'heading_4', 'heading_5', 'heading_6', 'heading_7',);
$insizes = array();
$sizeprices = array();
/* <!--- END SIZE CHART ---> */
and
/* <!--- SIZE CHART ---> */
$product_info_query = tep_db_query("select
p.products_id, pd.products_name, pd.products_description, p.products_model, p.products_quantity,
p.products_image, pd.products_url, p.products_price, p.products_tax_class_id, p.products_date_added,
p.products_date_available, p.manufacturers_id,
s.*
from
" . TABLE_PRODUCTS . " p,
" . TABLE_PRODUCTS_DESCRIPTION . " pd,
" . products_size_measurements . " s
where
p.products_status = '1' and
p.products_id = '" . (int)$HTTP_GET_VARS['products_id'] . "' and
pd.products_id = p.products_id and
s.product_id = p.products_id and
pd.language_id = '" . (int)$languages_id . "'");
/* <!--- END SIZE CHART ---> */
and
/* <!--- SIZE CHART ---> */
if ($products_options_name['products_options_name'] == 'Size') {
array_push($insizes, $products_options['products_options_values_name']);
}
$products_options_array[] = array(
'id' => $products_options['products_options_values_id'],
'text' => $products_options['products_options_values_name']);
/* $products_options_array[sizeof($products_options_array)-1]['text'] .= ' (' . $products_options[''] . $currencies->display_price($products_options['options_values_price'], tep_get_tax_rate($product_info['products_tax_class_id'])) .') '; */
$final = $products_options['options_values_price'] + $product_info['products_price'];
if ($new_price = tep_get_products_special_price($product_info['products_id'])) {
$price = '<del>' . $currencies->display_price($product_info['products_price'] + $products_options['options_values_price'], tep_get_tax_rate($product_info['products_tax_class_id'])) . '</del> <span class="productSpecialPrice">' . $currencies->display_price($new_price + $products_options['options_values_price'], tep_get_tax_rate($product_info['products_tax_class_id'])) . '</span>';
} else {
$price = $currencies->display_price($final, tep_get_tax_rate($product_info['products_tax_class_id']));
}
$name = $products_options['products_options_values_name'];
$sizeprices = array_push_assoc($sizeprices, "$name", "$price");
/* <!--- END SIZE CHART ---> */
Shouldn't I be able to use an if, else statement using flags (such as NA and 0) for the data stored in the DB? Something like so:
<?php if ($heading != "NA") {?>
<td><?php echo ($product_info["$heading"]); ?></td><?php }} else { ?>
<td>Price</td>
</tr>
<?php } ?>
and
<?php if ($measurement != 0) {?>
<td><?php echo number_format($product_info["$measurementx"], 0, '.', ''); ?>"<br><span class="sizeChartSm">(<?php echo number_format($product_info["$measurementx"] * 2.54, 1, '.', ''); ?>cm)</span></td>
<?php
}} else {
?>
<td>
<?php
echo $sizeprices["$size"];
?>
</td>
</tr>
<?php
}}
?>
However I can't seem to get the syntax right and keep throwing T_ELSE errors.
I think your error is coming from having too many brackets for the if else statement. Try this:
<?php if ($measurement != 0) {?>
<td><?php echo number_format($product_info["$measurementx"], 0, '.', ''); ?>"<br><span class="sizeChartSm">(<?php echo number_format($product_info["$measurementx"] * 2.54, 1, '.', ''); ?>cm)</span></td>
<?php
} else {
?>
<td>
<?php
echo $sizeprices["$size"];
?>
</td>
</tr>
<?php
}
?>
Also, your code would look way cleaner if you used short tags to echo your variables in the table like so:
<?php if ($measurement != 0) {?>
<td>
<?=number_format($product_info["$measurementx"], 0, '.', '')?>
<br>
<span class="sizeChartSm">
(<?=number_format($product_info["$measurementx"] * 2.54, 1, '.', '')?>cm)
</span>
</td>
<?php } else { ?>
<td>
<?=$sizeprices["$size"]?>
</td>
</tr>
<?php } ?>
skipping columns will cause the table to be drawn incorrectly.
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
... skipped
<td>3</td>
</tr>
would render as
1 2 3
1 3
not
1 2 3
1 3
You should modify $headings and $insizes to hide some of the columns or change the logic of your script. But I think for you will be easy to modify the arrays that you use to genertate the table.. Please show how you build these 2 arrays.

Categories