Pagination with Search Filter in CodeIgniter - codeigniter

When I search a keyword and paginate it, it returns data that matches the like query in the database.
A PHP Error was encountered
Severity: Warning
Message: count(): Parameter must be an array or an object that implements Countable
Filename: admin/view_member.php
Line Number: 105
Backtrace:
File: C:\xampp\htdocs\cms_new\application\views\admin\view_member.php
Line: 105
Function: _error_handler
File: C:\xampp\htdocs\cms_new\application\controllers\admin\Member.php
Line: 63
Function: view
File: C:\xampp\htdocs\cms_new\index.php
Line: 315
Function: require_once
MY Controller
$search = ($this->input->post("member_name"))? $this->input->post("member_name") : "NIL";
$search = ($this->uri->segment(3)) ? $this->uri->segment(3) : $search;
// pagination settings
$config = array();
$config['base_url'] = site_url("admin/member/index/$search");
$config['total_rows'] = $this->Model_member->record_count($search);
$config['per_page'] = "3";
$config["uri_segment"] = 4;
$choice = $config["total_rows"]/$config["per_page"];
$config["num_links"] = floor($choice);
// integrate bootstrap pagination
$config['full_tag_open'] = '<ul class="pagination">';
$config['full_tag_close'] = '</ul>';
$config['first_link'] = false;
$config['last_link'] = false;
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['prev_link'] = 'Prev';
$config['prev_tag_open'] = '<li class="prev">';
$config['prev_tag_close'] = '</li>';
$config['next_link'] = 'Next';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$this->pagination->initialize($config);
$data['page'] = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
// get books list
$data['users'] = $this->Model_member->fetch_data($config['per_page'], $data['page'], $search);
$data['pagination'] = $this->pagination->create_links();
$this->load->view('admin/view_header',$data);
$this->load->view('admin/view_member',$data);
$this->load->view('admin/view_footer');
My Model
function fetch_data($limit, $start, $st = NULL)
{
if($st == "NIL")
$st = "";
$this->db->select('*');
$this->db->from('tbl_member');
$this->db->like('member_name', $st);
$this->db->or_like('member_email', $st);
$this->db->limit($limit, $start);
$query = $this->db->get();
if ($query->num_rows() > 0) {
//var_dump($query->result());
foreach ($query->result() as $row) {
$data[] = $row;
}
//print_r($query);
return $data;
}
if ($query->num_rows() == 0) {
$this->session->set_flashdata('recoard','<div class="alert alert-danger text-center">Record Not Found! </div>');
}
return false;
}
function record_count($st = NULL)
{
if($st == "NIL")
$st = "";
$this->db->select('*');
$this->db->from('tbl_member');
$this->db->like('member_name', $st);
$this->db->or_like('member_email', $st);
$query = $this->db->get();
return $query->num_rows();
var_dump($query->num_rows());
}
My View
<?php
$user = count($users);
var_dump($user);
for ($i = 0; $i < $user; ++$i) {
if(! $users ){
// Faild Message
echo $this->session->flashdata('recoard');
}
else {
?>
<tbody>
<tr>
<td class="text-center"><img class="rounded-circle img-fluid avatar-40" src="<?php echo base_url();; ?>public/uploads/<?php echo $users[$i]->member_photo; ?>" alt="profile"></td>
<td><?php echo $users[$i]->member_name; ?></td>
<td><?php echo $users[$i]->member_email; ?><br>
<?php echo $users[$i]->member_mobile; ?></td>
<td><?php echo $users[$i]->member_city; ?><br>
<?php echo $users[$i]->member_state; ?><br>
<?php echo $users[$i]->member_country; ?></td>
<td><?php echo $users[$i]->member_address; ?></td>
<td>
<?php
if($users[$i]->member_access == 1)
{
echo '<span class="badge iq-bg-primary">Active</span></td>';
}
else
{
echo '<span class="badge iq-bg-warning">Inactive</span></td>';
}
?>
</td>
<td>
<div class="flex align-items-center list-user-action">
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Change Status" href="<?php echo base_url(); ?>admin/member/change_status/<?php echo $users[$i]->member_id; ?>" onClick="return confirm('Are you sure?');"><i class="ri-user-add-line"></i></a>
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Edit" href="<?php echo base_url(); ?>admin/member/edit/<?php echo $users[$i]->member_id; ?>"><i class="ri-pencil-line"></i></a>
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Delete" href="<?php echo base_url(); ?>admin/member/delete/<?php $users[$i]->member_id; ?>" onClick="return confirm('Are you sure?');"><i class="iq-bg-danger ri-delete-bin-line"></i></a>
</div>
</td>
</tr>
</tbody>
<?php } } ?>

you seem to not be returning an array to count & loop over, this is why you have the warning.
Also you have the failed message inside your loop that will make more errors later on.
Hope this helps & works for you
<?php
if (!$users || !is_array($users)) {
// Faild Message
echo $this->session->flashdata('recoard');
} else {
foreach ($users as $user) { ?>
<tbody>
<tr>
<td class="text-center"><img class="rounded-circle img-fluid avatar-40" src="<?php echo base_url("public/uploads/"); ?><?php echo $user->member_photo; ?>" alt="profile"></td>
<td><?php echo $user->member_name; ?></td>
<td><?php echo $user->member_email; ?><br>
<?php echo $user->member_mobile; ?></td>
<td><?php echo $user->member_city; ?><br>
<?php echo $user->member_state; ?><br>
<?php echo $user->member_country; ?></td>
<td><?php echo $user->member_address; ?></td>
<td>
<?php
if ($user->member_access == 1) {
echo '<span class="badge iq-bg-primary">Active</span></td>';
} else {
echo '<span class="badge iq-bg-warning">Inactive</span></td>';
}
?>
</td>
<td>
<div class="flex align-items-center list-user-action">
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Change Status" href="<?php echo base_url(); ?>admin/member/change_status/<?php echo $user->member_id; ?>" onClick="return confirm('Are you sure?');"><i class="ri-user-add-line"></i></a>
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Edit" href="<?php echo base_url(); ?>admin/member/edit/<?php echo $user->member_id; ?>"><i class="ri-pencil-line"></i></a>
<a data-toggle="tooltip" data-placement="top" title="" data-original-title="Delete" href="<?php echo base_url(); ?>admin/member/delete/<?php $user->member_id; ?>" onClick="return confirm('Are you sure?');"><i class="iq-bg-danger ri-delete-bin-line"></i></a>
</div>
</td>
</tr>
</tbody>
<?php }
} ?>

Related

datewise searching not working in pagination

My search result correctly displaying. But when I click the second page or pagination then all the data is displaying
my view - date selecting
Here I select the date using the date picker
<div class='floatl modal-form col-sm-12'>
<div class='col-sm-5'>
<input type='text' class='dateTablePicker' readonly id='dateTableFrom'
placeholder='date from'/>
</div>
<div class='col-sm-5'>
<input type='text' class='dateTablePicker' readonly id='dateTableTo'
placeholder='date to'/>
</div>
<div class='col-sm-2'>
<button class='btn-success' onclick="filterTable()"> Filter</button>
</div>
</div>
<div class='contentTable'>
<?php
$this->load->view("pages/tableData/leads_data");
?>
</div>
<script>
$(function () {
$(".dateTablePicker").datepicker({dateFormat: 'yy-mm-dd'});
});
function filterTable() {
$.ajax({
type: "POST",
url: "<?= site_url('OperationRouter/filterTableData'); ?>",
data: {dateTableFrom: $('#dateTableFrom').val(), dateTableTo: $('#dateTableTo').val()},
success: function (data) {
$(".contentTable").html(data);
}
});
}
leads_data//table data listing
The data displaying if the datefrom and dateto is isset then data displaying based on searching.
<?php
if (!isset($_SESSION['dateTableFrom'])) $_SESSION['dateTableFrom'] = '';
if (!isset($_SESSION['dateTableTo'])) $_SESSION['dateTableTo'] = '';
$dateTableFrom = $_SESSION['dateTableFrom'];
$dateTableTo = $_SESSION['dateTableTo'];
$page='leads';
$slno = 0;
// CONDITION QUERY
if (isset($_SESSION['export_Sql']))
$cql = $_SESSION['export_Sql'];
else if($dateTableFrom) {
$cql = '
select leads.id,leads.created,leads.product_id,
leads.company_id,leads.owner_id,leads.creator_id,
leads.title,leads.date,products.title as product,
leads.converted_flag,leads.status,
companies.title as company,admin.username
from admin admin,products products,leads leads,companies
companies
where products.id=leads.product_id
and companies.id=leads.company_id
and admin.id=leads.owner_id
and leads.remove_status = 1
and
( leads.creator_id = ' . $this->session-
>userdata['logged_admin'] . '
or FIND_IN_SET(leads.creator_id, ( select
GROUP_CONCAT(id) from admin
where parent_id =' . $this->session-
>userdata['logged_admin'] . ' ))
)
and STR_TO_DATE(leads.created,"%d-%m-%Y") >= "' . $dateTableFrom . '"
and
STR_TO_DATE(leads.created,"%d-%m-%Y") <= "' . $dateTableTo . '"
';
}
else
{
$cql = '
select leads.id,leads.created,leads.product_id,
leads.company_id,leads.owner_id,leads.creator_id,
leads.title,leads.date,products.title as product,
leads.converted_flag,leads.status,
companies.title as company,admin.username
from admin admin,products products,leads leads,companies
companies
where products.id=leads.product_id
and companies.id=leads.company_id
and admin.id=leads.owner_id
and leads.remove_status = 1
and
( leads.creator_id = ' . $this->session-
>userdata['logged_admin'] . '
or FIND_IN_SET(leads.creator_id, ( select
GROUP_CONCAT(id) from admin
where parent_id =' . $this->session-
>userdata['logged_admin'] . ' ))
)
';
}
if (isset($_SESSION['export_Ids']) && $_SESSION['export_Ids']) {
$cql .= " and leads.id in (" . $_SESSION['export_Ids'] . ") ";
}
if (isset($_SESSION['export_Order']) &&
$_SESSION['export_Order'])
$oql = $_SESSION['export_Order'];
else
$oql = ''; // ORDER QUERY
if (isset($_SESSION['export_Limit']))
$lql = $_SESSION['export_Limit'];
else
$lql='';
if (isset($_SESSION['export_Ids']) && $_SESSION['export_Ids']) // IF ID'S
THEN NO EXPORT LIMIT NEEDED
$lql = '';
$sql = $cql . $oql;
$itemcount = $this->OperationModel->getRowCount($sql);
$sql = $cql . $oql . $lql;
?>
<input type='hidden' id='selectedSql' value='<?= $cql ?>'/>
<input type='hidden' id='selectedOrder' value='<?= $oql ?>'/>
<input type='hidden' id='selectedLimit' value='<?= $lql ?>'/>
<?php
$slno = 0;
//$sql='select * from admin_types where remove_status = 1';
$tableArray['searchFields'] = 'leads.title';
$itemsperpage = 6;
$result = $this->OperationModel->getTableData($sql,
$tableArray['searchFields'], $itemsperpage);
if (isset($result['data'])) {
$admin_det = $this->Adminuser->getsingleadmin($this->session-
>userdata['logged_admin']);
?>
<div class='custom-data-table '>
<table class='customtable'>
<tr>
<th style='width:70px;' class='checker'>
<input type='checkbox' class='thCheckbox'/>
<div class='customCheckbox'></div>
</th>
<th style='width:60px;'> No</th>
<th style='width:230px;'>
Title
<div class='floatr'><i class='i-sorter icon-shuffle'
data='leads.title'
title='sort records by title'></i>
</div>
</th>
<th>
Date
<div class='floatr'><i class='i-sorter icon-shuffle'
data='leads.created'
title='sort records by date '></i>
</div>
</th>
<th>
Service
<div class='floatr'><i class='i-sorter icon-shuffle'
data='products.title'
title='sort records by date '></i>
</div>
</th>
<th>
Client
<div class='floatr'><i class='i-sorter icon-shuffle'
data='companies.title'
title='sort records by company'>
</i></div>
</th>
<th>
Owner
<div class='floatr'><i class='i-sorter icon-shuffle'
data='admin.username'
title='sort records by owner'></i></div>
</th>
<?php if ($page != 'excelexport') { ?>
<?php if ($admin_det[0]['user_type'] == 'admin' ||
$admin_det[0]['user_type'] == 2) { ?>
<th> Conversion
<div class='floatr'><i class='i-sorter icon-
shuffle' data='leads.converted_flag'
title='sort records by
conversion status'></i></div>
</th>
<?php } ?>
<!--
<th>
Status
</th>
!-->
<th> Actions</th>
<?php } ?>
</tr>
<?php
// $slno=intval($current_page);
if (isset($searchkey)) $searchkey = $searchkey; else $searchkey
= '**';
foreach ($result['data'] as $row) {
$slno++;
?>
<tr id='<?= $row['id'] ?>'>
<td>
<input type='checkbox' class='tdCheckbox'/>
<div id='<?= $row['id'] ?>' class='customCheckbox'>
</div>
</td>
<td> <?= $slno ?> </td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['title'], $searchkey) ?></td>
<td><?= $row['created'] ?></td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['product'], $searchkey) ?></td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['company'], $searchkey) ?></td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['username'], $searchkey) ?></td>
<!--
<td><?= $row['lead_status'] ? '<span
style="color:green">Active</span>' : '<span
style="color:orange">Inactive</span>' ?></td>
!-->
<?php if ($page != 'excelexport') { ?>
<?php if ($admin_det[0]['user_type'] == 'admin' ||
$admin_det[0]['user_type'] == 2) { ?>
<td>
<button class='status-button'
data-trigger='leads'
data-value='<?=
$row['converted_flag'] ?>'
data-raw='<?= $row['id'] ?>'
data-field='converted_flag'
data-success="<span
class='colorange'>DisConvert</span>"
data-failure="<span
class='colgreen'>Convert</span>">
<?= ($row['converted_flag'] == 1) ? "
<span class='colorange'>DisConvert</span>" : "<span
class='colgreen'>Convert</span>" ?>
</button>
</td>
<?php } ?>
<td>
<?php
if ($row['creator_id'] ==
$_SESSION['logged_admin'] || $admin_det[0]['user_type'] ==
'admin' || $admin_det[0]['user_type'] == 2) { ?>
<a class='modal-switch'
data-toggle='modal'
data-target='#getAppUsers'
data-ajax='createmeeting'>
<i class='fa fa-plus add-bt'></i>
Meeting
</a>
<a class='modal-switch'
data-toggle='modal'
data-target='#getAppUsers'
data-ajax='createlead' data-raw='<?=
$row['id'] ?>'>
<i class='fa fa-pencil ed-bt'></i>
</a>
<?php if ($admin_det[0]['user_type'] ==
'admin') { ?>
<a class='delete-trigger' data-
trigger='leads' data-raw='<?= $row['id'] ?>'>
<i class='fa fa-trash del-bt'></i>
</a>
<?php } ?>
<?php } ?>
<a class='modal-switch'
data-toggle='modal'
data-operation='view'
data-target='#getAppUsers'
data-ajax='createlead' data-raw='<?=
$row['id'] ?>'>
<i class='fa fa-eye ed-bt'></i>
</a>
</td>
<?php } ?>
</tr>
<?php
}
?>
</table>
</div>
<?php
/* THE PAGINATION PART */
$pagination['base_url'] = $page;
$pagination['itemsperpage'] = $itemsperpage;
$pagination['total_rows'] = $this->OperationModel->getRowCount($sql,
$tableArray['searchFields']);
/* THE PAGINATION PART */
if (isset($pagination))
echo $this->OperationModel->getPagination($pagination);
?>
<?php
} else {
echo " <span class='floatl no-match-span'> <i class='icon-magnifier'></i>
<span>Oopz , No data found in database for the corresponding item .
</span> </span> ";
}
?>
<?php
$this->session->unset_userdata('dateTableFrom');
?>
pagination part
Here is the pagination part
function getPagination($dataArray = '')
{
$msg = '';
if ($dataArray) {
$this->load->library('pagination');
$config['base_url'] = base_url() . $dataArray['base_url'];
//$config['base_url'] = base_url('controller_name/search');
$config['uri_segment'] = 2;
$config['total_rows'] = $dataArray['total_rows'];
$config['per_page'] = $dataArray['itemsperpage'];
$this->pagination->initialize($config);
$msg .= "<div class='pagination'>";
$msg .= $this->pagination->create_links();
$msg .= "</div>";
return $msg;
} else
return false;
}
You should pass the search params (filters) along with the ajax request. (along with the pagination)

pagination links will not work

On my users index page I am trying to set up the CI Pagination. But when I click on the 2nd link will load a error page "Unable to load page"; I have spent all day on it and will not load on the same page. I use hmvc I am not sure if that effects it?
How can I make it load on same page. As what most tutorials I have watched show. Like the tuts plus tutorial.
$config['base_url'] = 'http://localhost/codeigniter-project/';
URL http://localhost/codeigniter-project/admin/users/
Route $route['admin/users'] = "admin/user/users/index";
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends MX_Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/user/users', 'english');
$this->load->model('admin/user/users_model');
if (!$this->user->logged()) {
redirect('admin');
}
}
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['heading_title'] = $this->lang->line('heading_title');
$this->load->library('setting');
$this->load->library('pagination');
$config = array();
$config["base_url"] = base_url('admin/users');
$config['total_rows'] = $this->db->get('user')->num_rows();
$config["per_page"] = $this->setting->get('config_limit_admin');
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$data['user'] = $this->db->get('user', $config["per_page"], $this->uri->segment(3));
return $this->load->view('user/users_list', $data);
}
}
View
<?php echo Modules::run('admin/common/header/index');?><?php echo Modules::run('admin/common/column_left/index');?>
<div id="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<?php if ($this->session->flashdata('error')) { ?>
<div class="alert alert-danger"><i class="fa fa-times-circle"></i> <?php echo $this->session->flashdata('error');?></div>
<?php } ?>
<?php if ($this->session->flashdata('success')) { ?>
<div class="alert alert-success"><i class="fa fa-check-circle"></i> <?php echo $this->session->flashdata('success');?></div>
<?php } ?>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title"><?php echo $heading_title; ?></h3></div>
<div class="panel-body">
<?php
echo '<div class="table-responsive">';
echo '<table class="table table-striped table-bordered table-hover">';
echo '<thead>';
echo '<tr>';
echo '<td class="text-center">' . "User ID" . '</td>';
echo '<td class="text-center">' . "Username" . '</td>';
echo '<td class="text-center">' . "Status" . '</td>';
echo '<td class="text-center">' . "Date Added" . '</td>';
echo '<td class="text-center">' . "Action" . '</td>';
echo '</tr>';
echo '</thead>';
foreach ($user->result() as $row) {
echo '<tbody>';
echo '<tr>';
echo '<td class="text-center">' . $row->user_id .'</td>';
echo '<td class="text-center">' . $row->username .'</td>';
echo '<td class="text-center">' . $row->status .'</td>';
echo '<td class="text-center">' . $row->date_added .'</td>';
echo '<td class="text-center">' . anchor("admin/users/edit/" . $row->user_id, '<div class="btn btn-primary text-right" role="button"><i class="fa fa-pencil"></i>
Edit</div>') .'</td>';
echo '</tr>';
echo '</tbody>';
}
echo '</table>';
echo '</div>';
echo '<div class="row">';
echo '<div class="col-sm-6 text-left">';
echo $this->pagination->create_links();
echo '</div>';
echo '</div>';
?>
</div><!-- . Panel Panel-Body -->
</div><!-- . Panel Panel-Default -->
</div><!-- . Columns -->
</div><!-- . Row -->
</div><!-- . Container-fluid-->
</div><!-- #Content -->
<?php echo Modules::run('admin/common/footer/index');?>
I just had a brain storm and added $route['admin/users/(:num)'] = "admin/user/users/index/$1"; and now links work.

Magento - Controller to Ajax Estimate Shipping: Load Block and display phtml

I copied estimatePostAction and made estimateAjaxPostAction (overriding core - I did not hack the core). The controller action works as well (class Mage_Checkout_CartController).
Now I want to get/create a block for replacing shipping block after estimate shipping with ajax. I tried this:
public function estimateAjaxPostAction()
{
$country = (string) $this->getRequest()->getParam('country_id');
$postcode = (string) $this->getRequest()->getParam('estimate_postcode');
$city = (string) $this->getRequest()->getParam('estimate_city');
$regionId = (string) $this->getRequest()->getParam('region_id');
$region = (string) $this->getRequest()->getParam('region');
$this->_getQuote()->getShippingAddress()
->setCountryId($country)
->setCity($city)
->setPostcode($postcode)
->setRegionId($regionId)
->setRegion($region)
->setCollectShippingRates(true);
$this->_getQuote()->save();
//$this->_goBack();
$this->loadLayout();
$block = $this->getLayout()->createBlock('Mage_Checkout_Block_Cart_Shipping','checkout.cart.shipping.ajax',array('template' => 'checkout/cart/shipping.phtml'));
if($block) {
$response = array();
$response['shipping'] = $block->toHtml();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
}
}
The block checkout.cart.shipping.ajax was created. But toHtml() returns nothing.
My JSON returns:
{"shipping":""}
Why toHtml method doesn't work?
Edit: My block code (checkout/cart/shipping.phtml)
<?php /** #var $this Mage_Checkout_Block_Cart_Shipping */ ?>
<div class="row contem-shipping">
<div class="col-xs-10 shipping">
<div class="text-ship">
<h2><?php echo $this->__('Calcular o frete:') ?></h2>
<p><?php echo $this->__('Insira o CEP do endereço<br />no campo ao lado.') ?></p>
</div>
<div class="shipping-form">
<form action="<?php echo $this->getUrl('checkout/cart/estimatePost') ?>" method="post" id="shipping-zip-form">
<ul class="form-list">
<li class="no-display">
<div class="input-box">
<?php echo Mage::getBlockSingleton('directory/data')->getCountryHtmlSelect($this->getEstimateCountryId()) ?>
</div>
</li>
<?php if($this->getStateActive()): ?>
<li>
<label for="region_id"<?php if ($this->isStateProvinceRequired()) echo ' class="required"' ?>><?php if ($this->isStateProvinceRequired()) echo '<em>*</em>' ?><?php echo $this->__('State/Province') ?></label>
<div class="input-box">
<select id="region_id" name="region_id" title="<?php echo $this->__('State/Province') ?>" style="display:none;"<?php echo ($this->isStateProvinceRequired() ? ' class="validate-select"' : '') ?>>
<option value=""><?php echo $this->__('Please select region, state or province') ?></option>
</select>
<script type="text/javascript">
//<![CDATA[
$('region_id').setAttribute('defaultValue', "<?php echo $this->getEstimateRegionId() ?>");
//]]>
</script>
<input type="text" id="region" name="region" value="<?php echo $this->escapeHtml($this->getEstimateRegion()) ?>" title="<?php echo $this->__('State/Province') ?>" class="input-text" style="display:none;" />
</div>
</li>
<?php endif; ?>
<?php if($this->getCityActive()): ?>
<li>
<label for="city"<?php if ($this->isCityRequired()) echo ' class="required"' ?>><?php if ($this->isCityRequired()) echo '<em>*</em>' ?><?php echo $this->__('City') ?></label>
<div class="input-box">
<input class="input-text<?php if ($this->isCityRequired()):?> required-entry<?php endif;?>" id="city" type="text" name="estimate_city" value="<?php echo $this->escapeHtml($this->getEstimateCity()) ?>" />
</div>
</li>
<?php endif; ?>
<li>
<div class="input-box">
<input class="input-text validate-postcode<?php if ($this->isZipCodeRequired()):?> required-entry<?php endif;?>" type="text" id="postcode" name="estimate_postcode" value="<?php echo $this->escapeHtml($this->getEstimatePostcode()) ?>" />
</div>
</li>
</ul>
<div class="buttons-set">
<button id="button-cep" style="width: 100px;" type="button" title="<?php echo $this->__('Get a Quote') ?>" onclick="calculaFreteAjax(jQuery('#postcode').val()); return false;" class="btn btn-2 btn-2a"><?php echo $this->__('Get a Quote') ?></button>
</div>
</form>
<script type="text/javascript">
//<![CDATA[
new RegionUpdater('country', 'region', 'region_id', <?php echo $this->helper('directory')->getRegionJson() ?>);
//]]>
</script>
<?php $_shippingRateGroups = $this->getEstimateRates(); ?>
<?php if ($_shippingRateGroups): ?>
<form id="co-shipping-method-form" action="<?php echo $this->getUrl('checkout/cart/estimateUpdatePost') ?>">
<dl class="sp-methods">
<?php foreach ($_shippingRateGroups as $code => $_rates): ?>
<dt><?php echo $this->escapeHtml($this->getCarrierName($code)) ?></dt>
<dd>
<ul>
<?php foreach ($_rates as $_rate): ?>
<li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"';?>>
<?php if ($_rate->getErrorMessage()): ?>
<?php echo $this->escapeHtml($_rate->getErrorMessage()) ?>
<?php else: ?>
<input name="estimate_method" type="radio" value="<?php echo $this->escapeHtml($_rate->getCode()) ?>" id="s_method_<?php echo $_rate->getCode() ?>"<?php if($_rate->getCode()===$this->getAddressShippingMethod()) echo ' checked="checked"' ?> class="radio" />
<label for="s_method_<?php echo $_rate->getCode() ?>"><?php echo $this->escapeHtml($_rate->getMethodTitle()) ?>
<?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('tax')->displayShippingPriceIncludingTax()); ?>
<?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
<?php echo $_excl; ?>
<?php if ($this->helper('tax')->displayShippingBothPrices() && $_incl != $_excl): ?>
(<?php echo $this->__('Incl. Tax'); ?> <?php echo $_incl; ?>)
<?php endif; ?>
</label>
<?php endif ?>
</li>
<?php endforeach; ?>
</ul>
</dd>
<?php endforeach; ?>
</dl>
</form>
<?php endif; ?>
<script type="text/javascript">
//<![CDATA[
var coShippingMethodForm = new VarienForm('shipping-zip-form');
var countriesWithOptionalZip = <?php echo $this->helper('directory')->getCountriesWithOptionalZip(true) ?>;
coShippingMethodForm.submit = function () {
var country = $F('country');
var optionalZip = false;
for (i=0; i < countriesWithOptionalZip.length; i++) {
if (countriesWithOptionalZip[i] == country) {
optionalZip = true;
}
}
if (optionalZip) {
$('postcode').removeClassName('required-entry');
}
else {
$('postcode').addClassName('required-entry');
}
return VarienForm.prototype.submit.bind(coShippingMethodForm)();
}
//]]>
</script>
</div>
</div>
<div class="col-xs-6">
<?php
$totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount(); //total items in cart
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object
$subtotal = $totals["subtotal"]->getValue(); //Subtotal value
$grandtotal = $totals["grand_total"]->getValue(); //Grandtotal value
if(isset($totals['discount']) && $totals['discount']->getValue()) {
$discount = $totals['discount']->getValue(); //Discount value if applied
} else {
$discount = '';
}
$shipping = Mage::helper('checkout')->getQuote()->getShippingAddress()->getData();
$tax = $shipping["shipping_amount"];
/*if( $totals["tax"]->getValue()) {
$tax = $totals["tax"]->getValue(); //Tax value if present
} else {
$tax = '';
}*/
?>
<table class="totals-cart">
<tr>
<td class="total-tile">
Subtotal do pedido:
</td>
<td class="total-price">
<?php echo Mage::helper('core')->currency($subtotal, true, false); ?>
</td>
</tr>
<tr>
<td class="total-tile">
Frete:
</td>
<td class="total-price">
<?php echo Mage::helper('core')->currency($tax, true, false); ?>
</td>
</tr>
<?php if ($discount):?>
<tr>
<td class="total-tile">
Desconto:
</td>
<td class="total-price">
<?php echo Mage::helper('core')->currency($discount, true, false); ?>
</td>
</tr>
<?php endif;?>
</table>
</div>
</div>
<div class="row">
<div class="col-xs-16">
<div class="grand-total">
<p class="text">Total:</p>
<p class="price"><?php echo Mage::helper('core')->currency($grandtotal, true, false);?></p>
</div>
</div>
</div>
<script type="text/javascript">
function calculaFreteAjax(cep) {
jQuery('.contem-shipping .shipping').html('<span class="remove-frete" style="display: block; margin: 0 auto; width: 20px;" id="login-please-wait"><img src="http://sites.xpd.com.br/cpaps/skin/frontend/xpd/default/images/opc-ajax-loader.gif" class="v-middle" alt=""/></span>');
var param = {'country_id': 'BR','estimate_postcode': cep};
console.log(param);
jQuery.ajax({
type: "GET",
url: '<?php echo Mage::getBaseUrl().'checkout/cart/estimateAjaxPost/'; ?>', //My Custom Controller
data: param,
success: function(response) {
response = jQuery.parseJSON(response);
if(response.shipping) {
jQuery('.contem-shipping').parent().html(response.shipping);
}
else {
alert('Falha ao calcular o frete. Tente novamente.');
}
}
});
jQuery('#co-shipping-method-form dd input.radio').click(function(){
//I will submit the shipping method selected
});
}
</script>
Denis... I have modify code please check
public function estimateAjaxPostAction()
{
$country = (string) $this->getRequest()->getParam('country_id');
$postcode = (string) $this->getRequest()->getParam('estimate_postcode');
$city = (string) $this->getRequest()->getParam('estimate_city');
$regionId = (string) $this->getRequest()->getParam('region_id');
$region = (string) $this->getRequest()->getParam('region');
$this->_getQuote()->getShippingAddress()
->setCountryId($country)
->setCity($city)
->setPostcode($postcode)
->setRegionId($regionId)
->setRegion($region)
->setCollectShippingRates(true);
$this->_getQuote()->save();
$response = array();
$response['shipping']=$this->eastmatesajax();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
}
protected function eastmatesajax()
{
$layout=$this->getLayout();
$layout->getMessagesBlock()->setMessages(Mage::getSingleton('checkout/session')->getMessages(true),Mage::getSingleton('catalog/session')->getMessages(true));
$block = $this->getLayout()->createBlock('checkout/cart_shipping')->setTemplate( 'checkout/cart/shipping.phtml');
return $block->toHtml();
}
Updated block issue solved using $this->_getQuote()->collectTotals(); before $this->_getQuote()->save();

How to show children's subcategorie's of current categorie in Magento

I am trying to get my big catalog somewhat tablet friendly by offering an selection of tabs with sublevel links for my seperate categories. So if a user clicks a (1st level)head category it needs to display a nr of blocks which hold the picture, description and url of each direct child and a list of all the underlying (3rd level) child categories of the shown (2nd level) categorie. Would any off you guys be so kind to check my code?
<?php
$layer = Mage::getSingleton('catalog/layer');
$_category = $layer->getCurrentCategory();
$_categories = $_category->getCollection()
->addAttributeToSelect(array('url_key','name','image','all_children','is_anchor','description'))
->addAttributeToFilter('is_active', 1)
->addIdFilter($_category->getChildren())
->setOrder('position', 'ASC')
->joinUrlRewrite();
?>
<?php $children = explode( ",", $this->getCurrentCategory()->getChildren() ); ?>
<ul class="category-grid">
<div class="category-list">
<?php foreach( $children as $child ): ?>
<?php $_child = Mage::getModel( 'catalog/category' )->load( $child ); ?>
<li class="item">
<img title="<?php echo $this->htmlEscape($_child->getName()) ?>" src="<?php echo $this->htmlEscape($_child->getImageUrl()) ?>" alt="<?php echo $this->htmlEscape($_child->getName()) ?>" />
<div class="subcategory-title">
<?php echo $this->htmlEscape($_child->getName()) ?>
</div>
<div class="description-block"> <?php echo $_child->getDescription(); ?></div>
<div class="children-links"><?php
$_helper = Mage::helper("catalog/category");
$rootCat = Mage::app()->getStore()->getRootCategoryId();
$current = Mage::registry('current_category');
if ($child){
//look for anchestor
$parentid = $child->getParentId();
$parent = Mage::getModel("catalog/category")->load($parentid);
if($parentid != $rootCat)
{
//find the anchestor
show_cat($parent,$_helper,$rootCat);
}else{
//is root
$_subcategories = $child->getChildrenCategories();
echo $_child->getAll_Children();
if(count($_subcategories)>0){
echo '<ul>';
foreach($_subcategories as $_category){
echo '<li>';
echo ''.$_category->getName().'';
if($child->getId() == $_category->getId()){
$current = Mage::registry('current_category');
if ($current){
//handle current
$_current_subcategories = $current->getChildrenCategories();
if(count($_current_subcategories)>0){
//the current cat has childrens
echo '<ul>';
foreach($_current_subcategories as $_sub_category){
echo '<li>';
echo ''.$_sub_category->getName().'';
echo '</li>';
}
echo '</ul>';
}else{
//the current cat has no childrens
$current_parent = $current->getParentId();
$current_parent = Mage::getModel("catalog/category")->load($current_parent );
$_current_subcategories = $current_parent ->getChildrenCategories();
echo '<ul>';
foreach($_current_subcategories as $_sub_category){
echo '<li>';
echo ''.$_sub_category->getName().'';
echo '</li>';
}
echo '</ul>';
}
}
}
echo '</li>';
}
echo '</ul>';
}
}
}
?>
</div>
</li>
<?php endforeach ?>
</div>
</ul>
you can this by the below code and also refer link at bottom
you could be go with this
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry('current_category') ?>
<?php if (count($_categories) > 0): ?>
<ul class="category">
<?php foreach($_categories as $_category): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
<?php echo $_category->getName() ?>
</a>
<?php if ($currentCategory->getId() && $currentCategory->getId() == $_category->getId()): ?>
<?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
<?php $_subcategories = $_category->getChildrenCategories() ?>
<?php if (count($_subcategories) > 0): ?>
<ul class="subcategory">
<?php foreach($_subcategories as $_subcategory): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>">
<?php echo $_subcategory->getName() ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
EDIT
<ul class="subcategory">
<? foreach ($_categories as $_category):?>
<? if($_category->getIsActive()):
$cur_subcategory=Mage::getModel('catalog/category')->load($_category->getId());
$layer = Mage::getSingleton('catalog/layer');
$layer->setCurrentCategory($cur_subcategory);
?>
<li> <?php echo $_category->getName()?></li>
<? endif;?>
<?endforeach?>
</ul>
Or you can go throw this Detail documentation, i am sure that would be really helpful to you.
// get current category
$current_category = $layer->getCurrentCategory();
// get sub categories of current category
$parent_categories = Mage::getModel('catalog/category')->getCategories($current_category->getId());
// go through each sub category and get their sub categories.
foreach($parent_categories as $child_category)
{
$child_category_id = $child_category->getId();
$grandchild_categories = Mage::getModel('catalog/category')->getCategories($child_category_id);
}
Here is the tested code for showing sub categories. Just put this code above "Toolbar" code in your custom theme "Magento_catalog/templet/product/list.phtml"
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
$subcats = $category->getChildrenCategories();
$_helper = $this->helper('Magento\Catalog\Helper\Output');
$imageHelper = \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\Catalog\Helper\Image::class);
if(count ($subcats) > 0)
{
?>
<div class = "sub-cat-div">
<ul class = "sub-cat-main">
<?php
foreach ($subcats as $subcat) {
if ($subcat->getIsActive()) {
$_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
$_outputhelper = $this->helper('Magento\Catalog\Helper\Output');
$subcaturl = $_category->getUrl();
$_imgHtml = '';
if ($_imgUrl = $_category->getImageUrl()) {
$_imgHtml = '<img src="' . $_imgUrl . '" />';
$_imgHtml = $_outputhelper->categoryAttribute($_category, $_imgHtml, 'image');
echo '<li class="sub-cat-image">' . $_imgHtml . '<span style="background-color: rgba(255,255,255,0.9)" class="content bg-white"><strong>' . $_category->getName() . '</strong></span></li>';
}
else{
$_imgUrl = $imageHelper->getDefaultPlaceholderUrl('image');
$_imgHtml = '<img src="' . $_imgUrl . '" />';
$_imgHtml = $_outputhelper->categoryAttribute($_category, $_imgHtml, 'image');
echo '<li class="sub-cat-image">' . $_imgHtml . '<span style="background-color: rgba(255,255,255,0.9)" class="content bg-white"><strong>' . $_category->getName() . '</strong></span></li>';
}
}
} ?>
</ul>
</div>
<?php
}
?>

How to Display the categories in tree structure

How to display all the categories in tree structure alike in a pop up window ie.) if i click the select category button in my page it should show the popup window with the tree
structured categories.i tried like this which will show all the categories in dropdown that does not look good
<?php
$categories = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('*')->addIsActiveFilter();
$allcatid = array();
$k=0;
foreach ($categories as $c) {
$allcatid[$k] = $c->getId();
$k++;
}
$finalcat=array_shift($allcatid);
$root= Mage::app()->getStore()->getRootCategoryId();
?>
<select id="category" class="myinput-text required-entry widthinput" name="category" >
<?php foreach($allcatid as $keycat){?>
<option value="<?php echo $keycat;?>"><?php echo Mage::getModel("catalog/category")->load($keycat)->getName(); ?></option>
<?php } ?>
This will help you to fetch you category tree
<?php
$rootcatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);
function get_categories($categories) {
$array= '<ul>';
foreach($categories as $category) {
$cat = Mage::getModel('catalog/category')->load($category->getId());
$count = $cat->getProductCount();
$array .= '<li>'.''. $category->getName() . "(".$count.")\n";
if($category->hasChildren()) {
$children = Mage::getModel('catalog/category')->getCategories($category->getId());
$array .= get_categories($children);
}
$array .= '</li>';
}
return $array . '</ul>';
}
echo get_categories($categories); ?>
Output View
This code is included an end-level category with product count.
Step 1 Goto theme/layout/catalog.xml put this code in the file.
<reference name="left">
<block type="catalog/navigation" name="category_list_sidebar" template="catalog/navigation/categorymenu.phtml"/>
</reference>
Step 2 Goto theme/template/catalog/ and create navigation folder also create categorymenu.phtml file inside folder and put code into file.
<?php
$_helper = Mage::helper('catalog/category');
$_categories = $_helper->getStoreCategories();
$currentCategory = Mage::registry('current_category');
?>
<div class="block block-list block-categorys">
<div class="block-title">
<strong><span>Category</span></strong>
</div>
<div class="block-content">
<ul class="category_sub">
<?php
if (count($_categories) > 0){
global $index;
global $data;
foreach($_categories as $_category){
$check_child_class = check_child_par($_category->getId());
$collaps = ($check_child_class)? "<span class='show-cat'>+</span>" : "";
echo "<li class='".$check_child_class."'>";
echo "<a href='".$_helper->getCategoryUrl($_category)."'>".$_category->getName();
echo " (".product_count($_category->getId()).")";
echo "</a>".$collaps;
echo check_child($_category->getId());
echo "</li>";
}
}
?>
</ul>
</div>
</div>
<?php
function check_child($cid){
$_helper = Mage::helper('catalog/category');
$_subcategory = Mage::getModel('catalog/category')->load($cid);
$_subsubcategories = $_subcategory->getChildrenCategories();
if (count($_subsubcategories) > 0){
echo "<ul>";
foreach($_subsubcategories as $_subcate){
$check_child_class = check_child_par($_subcate->getId());
$collaps = ($check_child_class)? "<span class='show-cat'>+</span>" : "";
echo "<li class='".$check_child_class."'>";
echo "<a href='".$_helper->getCategoryUrl($_subcate)."'>".$_subcate->getName();
echo " (".product_count($_subcate->getId()).")";
echo "</a>".$collaps;
echo check_child($_subcate->getId());
echo "</li>";
}
echo "</ul>";
}else{
return "";
}
}
function check_child_par($cid){
$_subcat = Mage::getModel('catalog/category')->load($cid);
$_subsubcats = $_subcat->getChildrenCategories();
if (count($_subsubcats) > 0){
return "parent";
}else{
return "";
}
}
function product_count($cid){
$products_count = Mage::getModel('catalog/category')->load($cid)->getProductCount();
return $products_count;
}
?>
enter code here
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry('current_category') ?>
<?php if (count($_categories) > 0): ?>
<ul>
<?php foreach($_categories as $_category): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
<?php echo $_category->getName() ?>
</a>
<?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
<?php $_subcategories = $_category->getChildrenCategories() ?>
<?php if (count($_subcategories) > 0): ?>
<ul>
<?php foreach($_subcategories as $_subcategory): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>">
<?php echo $_subcategory->getName() ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
this will fetch all catgory and sub category,,,hope this will help you

Resources