I want to wrap my laravel query inside the cache::remember() method which is not big problem. My problem with it is that my query first calls the function from the controller and there is a file transaction.php in this file. I'm getting this function called and after it, I'm putting some where() conditions on this function return query at the end. The final query gives results, and I'm passing this into the Yajra datatable.
So in short, my query is not on the same file so that i can wrap inside the cache::remember() function.
How can I wrap my query, which is placed in two files, controller and transaction.php. I hope you understand.
Here is a function inside the controller:
public function index()
{
$is_admin = $this->businessUtil->is_admin(auth()->user());
if ( !$is_admin && !auth()->user()->hasAnyPermission(['sell.view', 'sell.create', 'direct_sell.access', 'direct_sell.view', 'view_own_sell_only', 'view_commission_agent_sell', 'access_shipping', 'access_own_shipping', 'access_commission_agent_shipping', 'so.view_all', 'so.view_own']) ) {
abort(403, 'Unauthorized action.');
}
$business_id = request()->session()->get('user.business_id');
$is_woocommerce = $this->moduleUtil->isModuleInstalled('Woocommerce');
$is_tables_enabled = $this->transactionUtil->isModuleEnabled('tables');
$is_service_staff_enabled = $this->transactionUtil->isModuleEnabled('service_staff');
$is_types_service_enabled = $this->moduleUtil->isModuleEnabled('types_of_service');
if (request()->ajax()) {
$payment_types = $this->transactionUtil->payment_types(null, true, $business_id);
$with = [];
$shipping_statuses = $this->transactionUtil->shipping_statuses();
$sale_type = !empty(request()->input('sale_type')) ? request()->input('sale_type') : 'sell';
$sells = $this->transactionUtil->getListSells($business_id, $sale_type, request()->customer_id);
$permitted_locations = auth()->user()->permitted_locations();
if ($permitted_locations != 'all') {
$sells->whereIn('transactions.location_id', $permitted_locations);
}
//Add condition for created_by,used in sales representative sales report
if (request()->has('created_by')) {
$created_by = request()->get('created_by');
if (!empty($created_by)) {
$sells->where('transactions.created_by', $created_by);
}
}
$partial_permissions = ['view_own_sell_only', 'view_commission_agent_sell', 'access_own_shipping', 'access_commission_agent_shipping'];
if (!auth()->user()->can('direct_sell.access')) {
$sells->where( function($q){
if (auth()->user()->hasAnyPermission(['view_own_sell_only', 'access_own_shipping'])) {
$q->where('transactions.created_by', request()->session()->get('user.id'));
}
//if user is commission agent display only assigned sells
if (auth()->user()->hasAnyPermission(['view_commission_agent_sell', 'access_commission_agent_shipping'])) {
$q->orWhere('transactions.commission_agent', request()->session()->get('user.id'));
}
});
}
if (!empty(request()->input('payment_status')) && request()->input('payment_status') != 'overdue') {
$sells->where('transactions.payment_status', request()->input('payment_status'));
} elseif (request()->input('payment_status') == 'overdue') {
$sells->whereIn('transactions.payment_status', ['due', 'partial'])
->whereNotNull('transactions.pay_term_number')
->whereNotNull('transactions.pay_term_type')
->whereRaw("IF(transactions.pay_term_type='days', DATE_ADD(transactions.transaction_date, INTERVAL transactions.pay_term_number DAY) < CURDATE(), DATE_ADD(transactions.transaction_date, INTERVAL transactions.pay_term_number MONTH) < CURDATE())");
}
//Add condition for location,used in sales representative expense report
if (request()->has('location_id')) {
$location_id = request()->get('location_id');
if (!empty($location_id)) {
$sells->where('transactions.location_id', $location_id);
}
}
if (!empty(request()->input('rewards_only')) && request()->input('rewards_only') == true) {
$sells->where(function ($q) {
$q->whereNotNull('transactions.rp_earned')
->orWhere('transactions.rp_redeemed', '>', 0);
});
}
if (!empty(request()->customer_id)) {
$customer_id = request()->customer_id;
$sells->where('contacts.id', $customer_id);
}
if (!empty(request()->start_date) && !empty(request()->end_date)) {
$start = request()->start_date;
$end = request()->end_date;
$sells->whereDate('transactions.transaction_date', '>=', $start)
->whereDate('transactions.transaction_date', '<=', $end);
}
//Check is_direct sell
if (request()->has('is_direct_sale')) {
$is_direct_sale = request()->is_direct_sale;
if ($is_direct_sale == 0) {
$sells->where('transactions.is_direct_sale', 0);
$sells->whereNull('transactions.sub_type');
}
}
//Add condition for commission_agent,used in sales representative sales with commission report
if (request()->has('commission_agent')) {
$commission_agent = request()->get('commission_agent');
if (!empty($commission_agent)) {
$sells->where('transactions.commission_agent', $commission_agent);
}
}
if ($is_woocommerce) {
$sells->addSelect('transactions.woocommerce_order_id');
if (request()->only_woocommerce_sells) {
$sells->whereNotNull('transactions.woocommerce_order_id');
}
}
if (request()->only_subscriptions) {
$sells->where(function ($q) {
$q->whereNotNull('transactions.recur_parent_id')
->orWhere('transactions.is_recurring', 1);
});
}
if (!empty(request()->list_for) && request()->list_for == 'service_staff_report') {
$sells->whereNotNull('transactions.res_waiter_id');
}
if (!empty(request()->res_waiter_id)) {
$sells->where('transactions.res_waiter_id', request()->res_waiter_id);
}
if (!empty(request()->input('sub_type'))) {
$sells->where('transactions.sub_type', request()->input('sub_type'));
}
if (!empty(request()->input('created_by'))) {
$sells->where('transactions.created_by', request()->input('created_by'));
}
if (!empty(request()->input('status'))) {
$sells->where('transactions.status', request()->input('status'));
}
if (!empty(request()->input('sales_cmsn_agnt'))) {
$sells->where('transactions.commission_agent', request()->input('sales_cmsn_agnt'));
}
if (!empty(request()->input('service_staffs'))) {
$sells->where('transactions.res_waiter_id', request()->input('service_staffs'));
}
$only_shipments = request()->only_shipments == 'true' ? true : false;
if ($only_shipments) {
$sells->whereNotNull('transactions.shipping_status');
}
if (!empty(request()->input('shipping_status'))) {
$sells->where('transactions.shipping_status', request()->input('shipping_status'));
}
if (!empty(request()->input('for_dashboard_sales_order'))) {
$sells->whereIn('transactions.status', ['partial', 'ordered'])
->orHavingRaw('so_qty_remaining > 0');
}
if ($sale_type == 'sales_order') {
if (!auth()->user()->can('so.view_all') && auth()->user()->can('so.view_own')) {
$sells->where('transactions.created_by', request()->session()->get('user.id'));
}
}
if (empty(request()->customer_id)) {
$sells->groupBy('transactions.id');
}
if (!empty(request()->suspended)) {
$transaction_sub_type = request()->get('transaction_sub_type');
if (!empty($transaction_sub_type)) {
$sells->where('transactions.sub_type', $transaction_sub_type);
} else {
$sells->where('transactions.sub_type', null);
}
$with = ['sell_lines'];
if ($is_tables_enabled) {
$with[] = 'table';
}
if ($is_service_staff_enabled) {
$with[] = 'service_staff';
}
$sales = $sells->where('transactions.is_suspend', 1)
->with($with)
->addSelect('transactions.is_suspend', 'transactions.res_table_id', 'transactions.res_waiter_id', 'transactions.additional_notes')
->get();
return view('sale_pos.partials.suspended_sales_modal')->with(compact('sales', 'is_tables_enabled', 'is_service_staff_enabled', 'transaction_sub_type'));
}
$with[] = 'payment_lines';
if (!empty($with)) {
$sells->with($with);
}
//$business_details = $this->businessUtil->getDetails($business_id);
if ($this->businessUtil->isModuleEnabled('subscription')) {
$sells->addSelect('transactions.is_recurring', 'transactions.recur_parent_id');
}
$sales_order_statuses = Transaction::sales_order_statuses();
$datatable = Datatables::of($sells)
->addColumn(
'action',
function ($row) use ($only_shipments, $is_admin, $sale_type) {
$html = '<div class="btn-group">
<button type="button" class="btn btn-info dropdown-toggle btn-xs"
data-toggle="dropdown" aria-expanded="false">' .
__("messages.actions") .
'<span class="caret"></span><span class="sr-only">Toggle Dropdown
</span>
</button>
<ul class="dropdown-menu dropdown-menu-left" role="menu">' ;
if (auth()->user()->can("sell.view") || auth()->user()->can("direct_sell.view") || auth()->user()->can("view_own_sell_only")) {
$html .= '<li><i class="fas fa-eye" aria-hidden="true"></i> ' . __("messages.view") . '</li>';
}
if (!$only_shipments) {
if ($row->is_direct_sale == 0) {
if (auth()->user()->can("sell.update")) {
$html .= '<li><a target="_blank" href="' . action('SellPosController#edit', [$row->id]) . '"><i class="fas fa-edit"></i> ' . __("messages.edit") . '</a></li>';
}
} elseif ($row->type == 'sales_order') {
if (auth()->user()->can("so.update")) {
$html .= '<li><a target="_blank" href="' . action('SellController#edit', [$row->id]) . '"><i class="fas fa-edit"></i> ' . __("messages.edit") . '</a></li>';
}
} else {
if (auth()->user()->can("direct_sell.update")) {
$html .= '<li><a target="_blank" href="' . action('SellController#edit', [$row->id]) . '"><i class="fas fa-edit"></i> ' . __("messages.edit") . '</a></li>';
}
}
$delete_link = '<li><i class="fas fa-trash"></i> ' . __("messages.delete") . '</li>';
if ($row->is_direct_sale == 0) {
if (auth()->user()->can("sell.delete")) {
$html .= $delete_link;
}
} elseif ($row->type == 'sales_order') {
if (auth()->user()->can("so.delete")) {
$html .= $delete_link;
}
} else {
if (auth()->user()->can("direct_sell.delete")) {
$html .= $delete_link;
}
}
}
if (config('constants.enable_download_pdf') && auth()->user()->can("print_invoice") && $sale_type != 'sales_order') {
$html .= '<li><i class="fas fa-print" aria-hidden="true"></i> ' . __("lang_v1.download_pdf") . '</li>';
if (!empty($row->shipping_status)) {
$html .= '<li><i class="fas fa-print" aria-hidden="true"></i> ' . __("lang_v1.download_paking_pdf") . '</li>';
}
}
if (auth()->user()->can("sell.view") || auth()->user()->can("direct_sell.access")) {
if (!empty($row->document)) {
$document_name = !empty(explode("_", $row->document, 2)[1]) ? explode("_", $row->document, 2)[1] : $row->document ;
$html .= '<li><i class="fas fa-download" aria-hidden="true"></i>' . __("purchase.download_document") . '</li>';
if (isFileImage($document_name)) {
$html .= '<li><i class="fas fa-image" aria-hidden="true"></i>' . __("lang_v1.view_document") . '</li>';
}
}
}
if ($is_admin || auth()->user()->hasAnyPermission(['access_shipping', 'access_own_shipping', 'access_commission_agent_shipping']) ) {
$html .= '<li><i class="fas fa-truck" aria-hidden="true"></i>' . __("lang_v1.edit_shipping") . '</li>';
}
if ($row->type == 'sell') {
if (auth()->user()->can("print_invoice")) {
$html .= '<li><i class="fas fa-print" aria-hidden="true"></i> ' . __("lang_v1.print_invoice") . '</li>
<li><i class="fas fa-file-alt" aria-hidden="true"></i> ' . __("lang_v1.packing_slip") . '</li>';
}
$html .= '<li class="divider"></li>';
if (!$only_shipments) {
if ($row->payment_status != "paid" && auth()->user()->can("sell.payments")) {
$html .= '<li><i class="fas fa-money-bill-alt"></i> ' . __("purchase.add_payment") . '</li>';
}
$html .= '<li><i class="fas fa-money-bill-alt"></i> ' . __("purchase.view_payments") . '</li>';
if (auth()->user()->can("sell.create")) {
$html .= '<li><i class="fas fa-copy"></i> ' . __("lang_v1.duplicate_sell") . '</li>
<li><i class="fas fa-undo"></i> ' . __("lang_v1.sell_return") . '</li>
<li><i class="fas fa-eye"></i> ' . __("lang_v1.view_invoice_url") . '</li>';
}
}
$html .= '<li><i class="fa fa-envelope" aria-hidden="true"></i>' . __("lang_v1.new_sale_notification") . '</li>';
} else {
$html .= '<li><i class="fas fa-paperclip" aria-hidden="true"></i>' . __("lang_v1.shipping_documents") . '</li>';
}
$html .= '</ul></div>';
return $html;
}
)
->removeColumn('id')
->editColumn(
'final_total',
'<span class="final-total" data-orig-value="{{$final_total}}">#format_currency($final_total)</span>'
)
->addColumn('products', function($row){
return $row->product_name;
})
->editColumn(
'unit_price',
'<span class="unit-price" data-orig-value="{{$unit_price}}">#format_currency($unit_price)</span>'
)
->editColumn(
'tax_amount',
'<span class="total-tax" data-orig-value="{{$tax_amount}}">#format_currency($tax_amount)</span>'
)
->editColumn(
'total_paid',
'<span class="total-paid" data-orig-value="{{$total_paid}}">#format_currency($total_paid)</span>'
)
->editColumn(
'total_before_tax',
'<span class="total_before_tax" data-orig-value="{{$total_before_tax}}">#format_currency($total_before_tax)</span>'
)
->editColumn(
'discount_amount',
function ($row) {
$discount = !empty($row->discount_amount) ? $row->discount_amount : 0;
if (!empty($discount) && $row->discount_type == 'percentage') {
$discount = $row->total_before_tax * ($discount / 100);
}
return '<span class="total-discount" data-orig-value="' . $discount . '">' . $this->transactionUtil->num_f($discount, true) . '</span>';
}
)
->editColumn('transaction_date', '{{#format_datetime($transaction_date)}}')
->editColumn(
'payment_status',
function ($row) {
$payment_status = Transaction::getPaymentStatus($row);
return (string) view('sell.partials.payment_status', ['payment_status' => $payment_status, 'id' => $row->id]);
}
)
->editColumn(
'types_of_service_name',
'<span class="service-type-label" data-orig-value="{{$types_of_service_name}}" data-status-name="{{$types_of_service_name}}">{{$types_of_service_name}}</span>'
)
->addColumn('total_remaining', function ($row) {
$total_remaining = $row->final_total - $row->total_paid;
$total_remaining_html = '<span class="payment_due" data-orig-value="' . $total_remaining . '">' . $this->transactionUtil->num_f($total_remaining, true) . '</span>';
return $total_remaining_html;
})
->addColumn('return_due', function ($row) {
$return_due_html = '';
if (!empty($row->return_exists)) {
$return_due = $row->amount_return - $row->return_paid;
$return_due_html .= '<span class="sell_return_due" data-orig-value="' . $return_due . '">' . $this->transactionUtil->num_f($return_due, true) . '</span>';
}
return $return_due_html;
})
->editColumn('invoice_no', function ($row) {
$invoice_no = $row->invoice_no;
if (!empty($row->woocommerce_order_id)) {
$invoice_no .= ' <i class="fab fa-wordpress text-primary no-print" title="' . __('lang_v1.synced_from_woocommerce') . '"></i>';
}
if (!empty($row->return_exists)) {
$invoice_no .= ' <small class="label bg-red label-round no-print" title="' . __('lang_v1.some_qty_returned_from_sell') .'"><i class="fas fa-undo"></i></small>';
}
if (!empty($row->is_recurring)) {
$invoice_no .= ' <small class="label bg-red label-round no-print" title="' . __('lang_v1.subscribed_invoice') .'"><i class="fas fa-recycle"></i></small>';
}
if (!empty($row->recur_parent_id)) {
$invoice_no .= ' <small class="label bg-info label-round no-print" title="' . __('lang_v1.subscription_invoice') .'"><i class="fas fa-recycle"></i></small>';
}
if (!empty($row->is_export)) {
$invoice_no .= '</br><small class="label label-default no-print" title="' . __('lang_v1.export') .'">'.__('lang_v1.export').'</small>';
}
return $invoice_no;
})
->editColumn('shipping_status', function ($row) use ($shipping_statuses) {
$status_color = !empty($this->shipping_status_colors[$row->shipping_status]) ? $this->shipping_status_colors[$row->shipping_status] : 'bg-gray';
$status = !empty($row->shipping_status) ? '<span class="label ' . $status_color .'">' . $shipping_statuses[$row->shipping_status] . '</span>' : '';
return $status;
})
->addColumn('conatct_name', '#if(!empty($supplier_business_name)) {{$supplier_business_name}}, <br> #endif {{$name}}')
->editColumn('quantity', '{{#format_quantity($quantity)}}')
->filterColumn('conatct_name', function ($query, $keyword) {
$query->where( function($q) use($keyword) {
$q->where('contacts.name', 'like', "%{$keyword}%")
->orWhere('contacts.supplier_business_name', 'like', "%{$keyword}%");
});
})
->addColumn('payment_methods', function ($row) use ($payment_types) {
$methods = array_unique($row->payment_lines->pluck('method')->toArray());
$count = count($methods);
$payment_method = '';
if ($count == 1) {
$payment_method = $payment_types[$methods[0]];
} elseif ($count > 1) {
$payment_method = __('lang_v1.checkout_multi_pay');
}
$html = !empty($payment_method) ? '<span class="payment-method" data-orig-value="' . $payment_method . '" data-status-name="' . $payment_method . '">' . $payment_method . '</span>' : '';
return $html;
})
->editColumn('status', function($row) use($sales_order_statuses, $is_admin){
$status = '';
if ($row->type == 'sales_order') {
if ($is_admin && $row->status != 'completed') {
$status = '<span class="edit-so-status label ' . $sales_order_statuses[$row->status]['class'] . '" data-href="'.action("SalesOrderController#getEditSalesOrderStatus", ['id' => $row->id]).'">' . $sales_order_statuses[$row->status]['label'] . '</span>';
} else {
$status = '<span class="label ' . $sales_order_statuses[$row->status]['class'] . '" >' . $sales_order_statuses[$row->status]['label'] . '</span>';
}
}
return $status;
})
->editColumn('so_qty_remaining', '{{#format_quantity($so_qty_remaining)}}')
->setRowAttr([
'data-href' => function ($row) {
if (auth()->user()->can("sell.view") || auth()->user()->can("view_own_sell_only")) {
return action('SellController#show', [$row->id]) ;
} else {
return '';
}
}]);
$rawColumns = ['final_total', 'unit_price', 'action', 'total_paid', 'total_remaining', 'payment_status', 'invoice_no', 'discount_amount', 'tax_amount', 'total_before_tax', 'shipping_status', 'types_of_service_name', 'payment_methods', 'return_due', 'conatct_name', 'status'];
return $datatable->rawColumns($rawColumns)
->make(true);
}
$business_locations = BusinessLocation::forDropdown($business_id, false);
$customers = Contact::customersDropdown($business_id, false);
$sales_representative = User::forDropdown($business_id, false, false, true);
//Commission agent filter
$is_cmsn_agent_enabled = request()->session()->get('business.sales_cmsn_agnt');
$commission_agents = [];
if (!empty($is_cmsn_agent_enabled)) {
$commission_agents = User::forDropdown($business_id, false, true, true);
}
//Service staff filter
$service_staffs = null;
if ($this->productUtil->isModuleEnabled('service_staff')) {
$service_staffs = $this->productUtil->serviceStaffDropdown($business_id);
}
$shipping_statuses = $this->transactionUtil->shipping_statuses();
return view('sell.index')
->with(compact('business_locations', 'customers', 'is_woocommerce', 'sales_representative', 'is_cmsn_agent_enabled', 'commission_agents', 'service_staffs', 'is_tables_enabled', 'is_service_staff_enabled', 'is_types_service_enabled', 'shipping_statuses'));
}
You can see attached images My aim is how i can use cache::remember on this query.
Controller file
transactions.php file
Extend the transactionUtil file to do the entire query. You also need to gather all parts that are used to construct the query to form a unique key for a unique combination of them. For example this could be a function in the transaction util:
function getFullResult($business_id, $sale_type) {
$queryParameters = array_merge(compact('business_id, sale_type'), request()->all()); // You can filter these into the ones that are used for the query only
$cacheDurationSeconds = 3600;
return Cache::remember('getFullResult'.md5(json_encode($queryParameters)), $cacheDurationSeconds, function () use ($business_id, $sale_type) {
$sells = $this->getListSells($business_id, $sale_type, request()->customer_id);
if (request()->only_subscriptions) {
$sells->where(function ($q) {
$q->whereNotNull('transactions.recur_parent_id')
->orWhere('transactions.is_recurring', 1);
});
}
if (!empty(request()->list_for) && request()->list_for == 'service_staff_report') {
$sells->whereNotNull('transactions.res_waiter_id');
}
// ....
return $sells->where('transactions.is_suspend', 1)
->with($with)
->addSelect('transactions.is_suspend', 'transactions.res_table_id', 'transactions.res_waiter_id', 'transactions.additional_notes')
->get();
});
}
Here I used md5 to generate the unique key since its fast and has an acceptably low likelyhood of hash collisions for this particular use case.
However given the complexity of the query you need to question the likelihood you get multiple of the same parameters in a request because if you won't then caching can't help.
I am nearing completion of this code / plugin and I just have one bit to finish up before we make it all pretty and presentable; I am attempting to get my PHP file to re-load/re-fresh with the POST variables sent from the AJAX file, all from the response of the AJAX send:
$("#CategoryTree").load("poster.php #CategoryTree");
Right now on clicking a list item the CSS fires, the ajax fires and responds, variables are sent (checked them in the action registry as well all good there) but the area I call to re-load with the poster.php #CategoryTree does not react, error 500 is thrown.
Here is my full Javascript code:
jQuery(document).ready(function($) {
$('#CategoryTree').on('click', 'input[type=checkbox]', function() {
var $this = $(this);
var data = '';
if ($this.is(":checked")) {
$this.addClass('selectCheckbox');
//$this.val("1");
data = {
action: 'catID_Callback',
catID: $this.attr('id'),
catState: 1
};
$.post(the_ajax_script.ajaxurl, data, function(response) {
//alert('Got this from the server: ' + response);
$("#CategoryTree").load("poster.php #CategoryTree");
//alert( "Load was performed." );});
console.log(response);
});
} else {
$this.removeClass('selectCheckbox');
//$this.val("0");
data = {
action: 'catID_Callback',
catID: $this.attr('id'),
catState: 0
};
$.post(the_ajax_script.ajaxurl, data, function(response) {
// alert('Got this from the server: ' + response);
console.log(response);
});
}
});
});
And here is the PHP code (Line 55 is where the check starts):
<?php
//$message = "Started";
//echo "<script type='text/javascript'>alert('$message');</script>";
$thearray = [];
$terms = get_terms("pa_mymelp");
foreach ( $terms as $term ) {
$categories = $term->name;
array_push($thearray, $categories);
}
$categoryLines = $thearray;
function buildCategoryTree($categoryLines, $separator) {
$catTree = array();
foreach ($categoryLines as $catLine) {
$path = explode($separator, $catLine);
$node = & $catTree;
foreach ($path as $cat) {
$cat = trim($cat);
if (!isset($node[$cat])) {
$node[$cat] = array();
}
$node = & $node[$cat];
}
}
return $catTree;
}
function displayCategoryTree($categoryTree, $indent = '') {
foreach ($categoryTree as $node => $children) {
echo $indent . $node . "\n";
displayCategoryTree($children, $indent . '|- ');
}
}
$categoryTree = buildCategoryTree($categoryLines, '/');
function displayHtmlCategoryTree($categoryTree, $id = null, $pathSeparator = '/', $parents = '') {
if (empty($categoryTree)) return '';
$str = '<ul' . (!empty($id) ? ' id="'.$id.'"' : '') . '>';
foreach ($categoryTree as $node => $children) {
$currentPath = $parents . (empty($parents) ? '' : $pathSeparator) . $node;
$thelink = '';
$opener = 0;
if (substr_count($currentPath, '/')==5){
$patterns = array(" ", "/", ".");
$thelink = 'http://caap.co.nz/?pa_mymelp=' . strtolower(str_replace($patterns, '-', $currentPath));
$str .= '<li title="' . $currentPath . '">' . '<input value ="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . '' . $node . '</label>' .
/*displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath) .
*/'</li>';}
else
{
$cat = 0;
$catState = 0;
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
if (isset($_POST['catState'])){
$catState = $_POST['catState'];
}
$str .= '<li title="' . $currentPath . '">' . '<input value="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . $node . '</label>';
if ($cat == $currentPath && $catState == 1 ){$str.=displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath);}
}
}
$str .= '</li></ul>';
return $str;
}
echo displayHtmlCategoryTree($categoryTree, "CategoryTree", '/');
/*
function add_query_vars_filter( $vars ){
foreach (array_keys(Contracts::$query_params) as $name)
$vars[] = $name;
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
*/
?>
Here is the pertinent code from the PHP file
$cat = 0;
$catState = 0;
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
if (isset($_POST['catState'])){
$catState = $_POST['catState'];
}
$str .= '<li title="' . $currentPath . '">' . '<input value="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . $node . '</label>';
if ($cat == $currentPath && $catState == 1 ){$str.=displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath);}
Remove semicolon after if curly braces. if{}; to if{}
if (isset($_POST['catID'])){$cat = $_POST['catID'];};
replace it to
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
Now your code looks like.
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
if (isset($_POST['catState'])){
$catState = $_POST['catState'];
}
$str .= '<li title="' . $currentPath . '">' . '<input value="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . $node . '</label>';
if ($cat == $currentPath && $catState == 1){
$str.=displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath);
}
i installed a Joomla template and some errors are appearing in homepage, the Errors are related to the Sp Page Builder component.
How can i fix these errors?
Here's a document with the erros - https://drive.google.com/open?id=0B1toGflgmV7fZi1SQ051QWZxZFE
And the site.php
<?php
/**
* Flex 1.0 #package SP Page Builder
* Template Name - Flex
* #author Aplikko http://www.aplikko.com
* #copyright Copyright (c) 2015 Aplikko
* #license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
// no direct access
defined('_JEXEC') or die;
JLoader::register('JHtmlString', JPATH_LIBRARIES.'/joomla/html/html/string.php');
AddonParser::addAddon('sp_latest_posts','sp_latest_posts_addon');
function get_categories($parent=1) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select('*')
->from($db->quoteName('#__categories'))
->where($db->quoteName('extension') . ' = ' . $db->quote('com_content'))
->where($db->quoteName('published') . ' = ' . $db->quote(1))
->where($db->quoteName('parent_id') . ' = ' . $db->quote($parent))
->order($db->quoteName('created_time') . ' DESC');
$db->setQuery($query);
$cats = $db->loadObjectList();
$categories = array($parent);
foreach ($cats as $key => $cat) {
$categories[] = $cat->id;
}
return $categories;
}
function sp_latest_posts_addon($atts){
extract(spAddonAtts(array(
"title" => '',
"heading_selector" => 'h3',
"title_fontsize" => '',
"title_text_color" => '',
"title_margin_top" => '',
"title_margin_bottom" => '',
"show_image" => '',
"show_date" => '',
"show_category" => '',
"show_intro_text" => '',
"show_author" => '',
"item_limit" => '',
"intro_text_limit" => '100',
"column_no" => '3',
"image_alignment" => '',
"category" => '',
"style" => '',
"class" => '',
), $atts));
$app = JFactory::getApplication();
$doc = JFactory::getDocument();
// Database Query
require_once JPATH_SITE . '/components/com_content/helpers/route.php';
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select('a.*')
->from($db->quoteName('#__content', 'a'))
->select($db->quoteName('b.alias', 'category_alias'))
->select($db->quoteName('b.title', 'category'))
->join('LEFT', $db->quoteName('#__categories', 'b') . ' ON (' . $db->quoteName('a.catid') . ' = ' . $db->quoteName('b.id') . ')')
->where($db->quoteName('b.extension') . ' = ' . $db->quote('com_content'))
->where($db->quoteName('a.state') . ' = ' . $db->quote(1))
->where($db->quoteName('a.catid')." IN (" . implode( ',', get_categories($category) ) . ")")
->where($db->quoteName('a.access')." IN (" . implode( ',', $authorised ) . ")")
->order($db->quoteName('a.created') . ' DESC')
->setLimit($item_limit);
$db->setQuery($query);
$items = $db->loadObjectList();
// End Database Query
$style == 'flex' ? $flex_style = ' flex' : '';
$style == 'blog' ? $blog_style = ' blog' : '';
$blog_style = $output = '<div class="sppb-addon sppb-addon-latest-posts'.$flex_style.$blog_style.' sppb-row ' . $class . '">';
if ($title) {
$output .= '<div class="sppb-section-title">';
$output .= '<'.$heading_selector.' class="sppb-addon-title" style="' . $title_style . '"> ' . $title . '</' . $heading_selector . '>';
$output .= '</div>'; // END :: title
}
$output .= '<div class="sppb-addon-content">';
$output .= '<div class="latest-posts clearfix">';
foreach(array_chunk($items, $column_no) as $items) {
$output .= '<div>';
foreach ($items as $item) {
$item->slug = $item->id . ':' . $item->alias;
$item->catslug = $item->catid . ':' . $item->category_alias;
$item->user = JFactory::getUser($item->created_by)->name;
if ($access || in_array($item->access, $authorised)) {
// We know that user has the privilege to view the article
$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catid, $item->language));
$item->catlink = JRoute::_(ContentHelperRoute::getCategoryRoute($item->catslug, $item->catid, $item->language));
} else {
$item->link = JRoute::_('index.php?option=com_users&view=login');
$item->catlink = JRoute::_('index.php?option=com_users&view=login');
}
$tplParams = JFactory::getApplication()->getTemplate(true)->params;
$params = $item->params;
$attribs = json_decode($item->attribs);
$images = json_decode($item->images);
$imgsize = $tplParams->get('blog_list_image', 'default');
$intro_image = '';
if(isset($attribs->spfeatured_image) && $attribs->spfeatured_image != '') {
if($imgsize == 'default') {
$intro_image = $attribs->spfeatured_image;
} else {
$intro_image = $attribs->spfeatured_image;
$basename = basename($intro_image);
$list_image = JPATH_ROOT . '/' . dirname($intro_image) . '/' . JFile::stripExt($basename) . '_'. $imgsize .'.' . JFile::getExt($basename);
if(file_exists($list_image)) {
$intro_image = JURI::root(true) . '/' . dirname($intro_image) . '/' . JFile::stripExt($basename) . '_'. $imgsize .'.' . JFile::getExt($basename);
}
}
} elseif(isset($images->image_intro) && !empty($images->image_intro)) {
$intro_image = $images->image_intro;
}
if($column_no == '1') {
if ($show_image) {
$image_alignment == 'left' ? $img_column = 'sppb-col-sm-4 column-1 pull-left match-height' : $img_column = 'sppb-col-sm-4 column-1 pull-right match-height';
}
if ($show_image) {
$image_alignment == 'right' ? $content_column = 'sppb-col-sm-8 column-1 pull-left match-height' : $content_column = 'sppb-col-sm-8 column-1 pull-right match-height';
} else {
$image_alignment == 'right' ? $content_column = 'sppb-col-sm-12 column-1' : $content_column = 'sppb-col-sm-12 column-1';
}
$h2style = ' style="font-size:180%;line-height:1.4;"';
$img_wrapper_margin = ' style="margin:0;"';
if ($image_alignment == 'left') {
$inner_padding = ' style="padding:0 0 0 30px;"';
} else {
$inner_padding = ' style="padding:0 30px 0 0;"';
}
}
// match-height
$column_no > '1' ? $match_height = ' match-height' : '';
// Flex Style
if($style == 'flex') {
$output .= '<div class="latest-post sppb-col-sm-' . round(12/$column_no) . ' columns-'.$column_no.'">';
$output .= '<div class="latest-post-item">';
if($column_no == '1') {
$output .= '<div class="row-fluid">';
}
if(!empty($intro_image) || (isset($images->image_intro) && !empty($images->image_intro))) {
if ($show_image) {
if($column_no == '1') {
$output .= '<div style="padding:0" class="'.$img_column.'">';
}
$output .= '<div class="img-wrapper">';
$output .= '<img class="post-img" src="' . $intro_image . '" alt="' . $item->title . '" /><div class="caption-content">' . $item->title . '<em class="caption-category"><span class="posted-in">'. JText::_('COM_SPPAGEBUILDER_ADDON_POSTED_IN') .'</span>'. $item->category . '</em></div>';
$output .= '</div>';
if($column_no == '1') {
$output .= '</div>';
}
}
}
if($column_no == '1') {
$output .= '<div'.$inner_padding.' class="'.$content_column.'">';
}
$output .= '<div class="latest-post-inner match-height">';
if (($show_date || $show_intro_text || $show_author) != 1) {
$output .= '<h2 style="margin:0" class="entry-title">' . $item->title . '</h2>';
} else {
$output .= '<h2'.$h2style.' class="entry-title">' . $item->title . '</h2>';
}
if ($show_date) {
$output .= '<div class="entry-meta"><span class="entry-date">' . JHtml::_('date', $item->created, 'DATE_FORMAT_LC1') . '</span></div>';
}
if ($show_intro_text) {
$output .= '<p class="intro-text" >' . JHtml::_('string.truncate', strip_tags($item->introtext), $intro_text_limit) . '</p>';
}
$show_author || $show_category ? $output .= '<hr />' : '';
if ($show_author) {
$output .= '<span class="post-author"><span class="entry-author">' . JText::_('COM_SPPAGEBUILDER_ADDON_POSTED_BY'). '</span> ' . $item->user . '</span>';
}
if ($show_category) {
$show_author ? $posted_in_category = ' cat-inline' : '';
$output .= '<span class="category'.$posted_in_category.'"><span class="posted-in">'. JText::_('COM_SPPAGEBUILDER_ADDON_CATEGORY') .'</span>'. $item->category . '</span>';
}
if($column_no == '1') {
$output .= '</div>';
$output .= '</div>';
}
$output .= '</div>';
if($column_no == '1') {
$output .= '<div class="post-divider"></div>';
}
$output .= '</div>';
// Default & Blog styles
} else {
$output .= '<div class="latest-post sppb-col-sm-' . round(12/$column_no) . ' columns-'.$column_no.'">';
$output .= '<div class="latest-post-inner' . $match_height . '">';
if($column_no == '1') {
$output .= '<div class="row-fluid">';
}
if ($show_image) {
if($column_no == '1') {
$output .= '<div class="'.$img_column.'">';
}
$output .= '<div'.$img_wrapper_margin.' class="img-wrapper">';
$output .= '<img class="post-img" src="' . $intro_image . '" alt="' . $item->title . '" />';
$output .= '</div>';
if($column_no == '1') {
$output .= '</div>';
}
}
if($column_no == '1') {
$output .= '<div class="'.$content_column.'">';
}
if ($show_date) {
$output .= '<div class="entry-meta"><span class="entry-date"> ' . JHtml::_('date', $item->created, 'DATE_FORMAT_LC1') . '</span></div>';
}
$output .= '<h2'.$h2style.' class="entry-title">' . $item->title . '</h2>';
if ($show_intro_text) {
$output .= '<p class="intro-text" >' . JHtml::_('string.truncate', strip_tags($item->introtext), $intro_text_limit) . '</p>';
}
$show_author || $show_category ? $output .= '<hr />' : '';
if ($show_author) {
$output .= '<span class="post-author"><span class="entry-author">' . JText::_('COM_SPPAGEBUILDER_ADDON_POSTED_BY'). ' ' . $item->user . '</span></span>';
}
if ($show_category) {
$show_author ? $posted_in_category = ' cat-inline' : '';
$output .= '<span class="category'.$posted_in_category.'"><span class="posted-in">'. JText::_('COM_SPPAGEBUILDER_ADDON_CATEGORY') .'</span>'. $item->category . '</span>';
}
if($column_no == '1') {
$output .= '</div>';
$output .= '</div>';
}
$output .= '</div>';
}
$output .= '</div>';
}
$output .= '</div>';
}
$output .= '</div>';
$output .= '</div>';
$output .= '</div>';
$column_no == '1' ? $column_no_1 = '.column-1 {margin:10px auto;padding:0!important;}' : '';
// Add styles #media rulepost-img
if($style == 'flex') {
$custom_style = ''
. '#media screen and (max-width: 768px) {'
. $column_no_1
. '.img-wrapper a {font-size:150%;line-height:1.5;}'
. '}';
$doc->addStyleDeclaration($custom_style);
}
if ($column_no>='3') {
$custom_style_3 = ''
. '#media screen and (min-width: 992px) and (max-width: 1199px){'
. '.columns-'.$column_no.'{width:33.3333%;}'
. '}'
. '#media screen and (min-width: 768px) and (max-width: 991px){'
. '.columns-'.$column_no.'{width:50%}'
. '}';
$doc->addStyleDeclaration($custom_style_3);
}
if($column_no=='5') {
$custom_style_5 = ''
. '.columns-'.$column_no.' {width:20%}'
. '#media screen and (min-width: 992px) and (max-width: 1199px){'
. '.columns-'.$column_no.'{width:33.3333%;}'
. '}'
. '#media screen and (min-width: 768px) and (max-width: 991px){'
. '.columns-'.$column_no.'{width:50%}'
. '}'
. '#media screen and (max-width: 767px){'
. '.columns-'.$column_no.'{width:100%}'
. '}';
$doc->addStyleDeclaration($custom_style_5);
}
return $output;
}
Thanks!
There is many errors, but all of them are variable that have not been declared before using it, as example :
$style == 'flex' ? $flex_style = ' flex' : '';
$style == 'blog' ? $blog_style = ' blog' : '';
$blog_style = $output = '<div class="sppb-addon sppb-addon-latest-posts'.$flex_style.$blog_style.' sppb-row ' . $class . '">';
In this case $flex_style and $blog_style are not declared, you should write this instead :
$flex_style = style == 'flex' ? ' flex' : '';
$blog_style = $style == 'blog' ? ' blog' : '';
That is just an example, but if you search a little you'll find other issue like this one.
I have a php script which creates its own button, as I am using an open source framework. What I want is to use an image to create a button instead of a the link the is created. Here is the line for which I need the button:
<td class="main button_marg"><?php echo tep_draw_button(IMAGE_BUTTON_REVIEWS . (($reviews['count'] > 0) ? ' (' . $reviews['count'] . ')' : ''), 'comment', tep_href_link(FILENAME_PRODUCT_REVIEWS, tep_get_all_get_params())); ?></td>
That is the script I am using to create the review button, but I would like to insert an image into it. Any ideas would be most appreciative.
This is the code for tep_draw_button() function:
function tep_draw_button($title = null, $icon = null, $link = null, $priority = null, $params = null) {
static $button_counter = 1;
$types = array('submit', 'button', 'reset');
if ( !isset($params['type']) ) {
$params['type'] = 'submit';
}
if ( !in_array($params['type'], $types) ) {
$params['type'] = 'submit';
}
if ( ($params['type'] == 'submit') && isset($link) ) {
$params['type'] = 'button';
}
if (!isset($priority)) {
$priority = 'secondary';
}
$button = '<span class="tdbLink">';
if ( ($params['type'] == 'button') && isset($link) ) {
$button .= '<a id="tdb' . $button_counter . '" href="' . $link . '"';
if ( isset($params['newwindow']) ) {
$button .= ' target="_blank"';
}
} else {
$button .= '<button id="tdb' . $button_counter . '" type="' . tep_output_string($params['type']) . '"';
}
if ( isset($params['params']) ) {
$button .= ' ' . $params['params'];
}
$button .= '>' . $title;
if ( ($params['type'] == 'button') && isset($link) ) {
$button .= '</a>';
} else {
$button .= '</button>';
}
$button .= '</span><script type="text/javascript">$("#tdb' . $button_counter . '").button(';
$args = array();
if ( isset($icon) ) {
if ( !isset($params['iconpos']) ) {
$params['iconpos'] = 'left';
}
if ( $params['iconpos'] == 'left' ) {
$args[] = 'icons:{primary:"ui-icon-' . $icon . '"}';
} else {
$args[] = 'icons:{secondary:"ui-icon-' . $icon . '"}';
}
}
if (empty($title)) {
$args[] = 'text:false';
}
if (!empty($args)) {
$button .= '{' . implode(',', $args) . '}';
}
$button .= ').addClass("ui-priority-' . $priority . '").parent().removeClass("tdbLink");</script>';
$button_counter++;
return $button;
}
?>
You can probably override the style by using some css:
#your_button_id{ background: url(); height: x; width: x; etc... }
.your_button_class{ background: url(); height: x; width: x; etc... }
Try this:
To call the button, use the function with the parameters as they are below:
$image['src'] = 'http://yoururl.com/image.jpg'; // Image Source
$image['height'] = 600; // Image Height
$image['width'] = 300; // Image Width
tep_draw_button(IMAGE_BUTTON_REVIEWS . (($reviews['count'] > 0) ? ' (' . $reviews['count'] . ')' : ''), 'comment', tep_href_link(FILENAME_PRODUCT_REVIEWS, tep_get_all_get_params()), null, null, $image);
Then modify the tep_draw_button function like so. If you have an image source in the function parameter, the image will be placed in as a link rather than as a button.
<?
function tep_draw_button($title = null, $icon = null, $link = null, $priority = null, $params = null, $image = null) {
static $button_counter = 1;
if($image != null){
$button = '<span class="tdbLink">';
$button .= '<a id="tdb' . $button_counter . '" href="' . $link . '"';
$button .= '><img src="'. $image['src'] .'"';
if(is_numeric($image['height'])) $button .= ' height="'.$image['height'].'"';
if(is_numeric($image['width'])) $button .= ' width="'.$image['width'].'"';
$button .= 'alt="'.$title.'" /></a></span>';
}else{
$types = array('submit', 'button', 'reset');
if ( !isset($params['type']) ) {
$params['type'] = 'submit';
}
if ( !in_array($params['type'], $types) ) {
$params['type'] = 'submit';
}
if ( ($params['type'] == 'submit') && isset($link) ) {
$params['type'] = 'button';
}
if (!isset($priority)) {
$priority = 'secondary';
}
$button = '<span class="tdbLink">';
if ( ($params['type'] == 'button') && isset($link) ) {
$button .= '<a id="tdb' . $button_counter . '" href="' . $link . '"';
if ( isset($params['newwindow']) ) {
$button .= ' target="_blank"';
}
} else {
$button .= '<button id="tdb' . $button_counter . '" type="' . tep_output_string($params['type']) . '"';
}
if ( isset($params['params']) ) {
$button .= ' ' . $params['params'];
}
$button .= '>' . $title;
if ( ($params['type'] == 'button') && isset($link) ) {
$button .= '</a>';
} else {
$button .= '</button>';
}
$button .= '</span><script type="text/javascript">$("#tdb' . $button_counter . '").button(';
$args = array();
if ( isset($icon) ) {
if ( !isset($params['iconpos']) ) {
$params['iconpos'] = 'left';
}
if ( $params['iconpos'] == 'left' ) {
$args[] = 'icons:{primary:"ui-icon-' . $icon . '"}';
} else {
$args[] = 'icons:{secondary:"ui-icon-' . $icon . '"}';
}
}
if (empty($title)) {
$args[] = 'text:false';
}
if (!empty($args)) {
$button .= '{' . implode(',', $args) . '}';
}
$button .= ').addClass("ui-priority-' . $priority . '").parent().removeClass("tdbLink");</script>';
$button_counter++;
}
return $button;
}
?>
Let me know if this works, or if you need it tweaked at all. It's hard for me to test since I don't have an oscommerce instance on my machine to test on.