Codeigniter 3.1.0 & Bootstrap Pagination Links - codeigniter

On my codeigniter pagination links I am using bootstrap 3 +
When I am on the very first link it hides the << which goes back to start when I click on it.
1 2 >>
Question How can I make the codeigniter pagination all ways display << >> I have tried Always show Previous & Next links using CodeIgniter Pagination Class but is for CI2
$config['base_url'] = base_url('forum/?fid=' . $this->input->get('fid') . $url);
$config['total_rows'] = $this->thread_model->total_threads($this->input->get('fid'));
$config['per_page'] = $this->config->item('config_limit_admin');
$config['page_query_string'] = TRUE;
$config["full_tag_open"] = '<ul class="pagination">';
$config["full_tag_close"] = '</ul>';
$config["first_link"] = "«";
$config["first_tag_open"] = "<li>";
$config["first_tag_close"] = "</li>";
$config["last_link"] = "»";
$config["last_tag_open"] = "<li>";
$config["last_tag_close"] = "</li>";
$config['next_link'] = '»';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '<li>';
$config['prev_link'] = '«';
$config['prev_tag_open'] = '<li>';
$config['prev_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['pagination'] = $this->pagination->create_links();

I have just override the create_links() of core library in slightly different way to achieve this. So All you have to do is create a file name My_Pagination.php inapplication/libraries and put this code there (Code copied from create_link() method from core library Pagination.php)
My_Pagination.php file (Codeigniter 3.1.0)
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Pagination extends CI_Pagination {
public function create_links() {
if ($this->total_rows == 0 OR $this->per_page == 0) {
return '';
}
// Calculate the total number of pages
$num_pages = (int) ceil($this->total_rows / $this->per_page);
if ($num_pages === 1) {
return '';
}
// Check the user defined number of links.
$this->num_links = (int) $this->num_links;
if ($this->num_links < 0) {
show_error('Your number of links must be a non-negative number.');
}
// Keep any existing query string items.
// Note: Has nothing to do with any other query string option.
if ($this->reuse_query_string === TRUE) {
$get = $this->CI->input->get();
// Unset the controll, method, old-school routing options
unset($get['c'], $get['m'], $get[$this->query_string_segment]);
} else {
$get = array();
}
// Put together our base and first URLs.
// Note: DO NOT append to the properties as that would break successive calls
$base_url = trim($this->base_url);
$first_url = $this->first_url;
$query_string = '';
$query_string_sep = (strpos($base_url, '?') === FALSE) ? '?' : '&';
// Are we using query strings?
if ($this->page_query_string === TRUE) {
// If a custom first_url hasn't been specified, we'll create one from
// the base_url, but without the page item.
if ($first_url === '') {
$first_url = $base_url;
// If we saved any GET items earlier, make sure they're appended.
if (!empty($get)) {
$first_url .= $query_string_sep . http_build_query($get);
}
}
// Add the page segment to the end of the query string, where the
// page number will be appended.
$base_url .= $query_string_sep . http_build_query(array_merge($get, array($this->query_string_segment => '')));
} else {
// Standard segment mode.
// Generate our saved query string to append later after the page number.
if (!empty($get)) {
$query_string = $query_string_sep . http_build_query($get);
$this->suffix .= $query_string;
}
// Does the base_url have the query string in it?
// If we're supposed to save it, remove it so we can append it later.
if ($this->reuse_query_string === TRUE && ($base_query_pos = strpos($base_url, '?')) !== FALSE) {
$base_url = substr($base_url, 0, $base_query_pos);
}
if ($first_url === '') {
$first_url = $base_url . $query_string;
}
$base_url = rtrim($base_url, '/') . '/';
}
// Determine the current page number.
$base_page = ($this->use_page_numbers) ? 1 : 0;
// Are we using query strings?
if ($this->page_query_string === TRUE) {
$this->cur_page = $this->CI->input->get($this->query_string_segment);
} elseif (empty($this->cur_page)) {
// Default to the last segment number if one hasn't been defined.
if ($this->uri_segment === 0) {
$this->uri_segment = count($this->CI->uri->segment_array());
}
$this->cur_page = $this->CI->uri->segment($this->uri_segment);
// Remove any specified prefix/suffix from the segment.
if ($this->prefix !== '' OR $this->suffix !== '') {
$this->cur_page = str_replace(array($this->prefix, $this->suffix), '', $this->cur_page);
}
} else {
$this->cur_page = (string) $this->cur_page;
}
// If something isn't quite right, back to the default base page.
if (!ctype_digit($this->cur_page) OR ( $this->use_page_numbers && (int) $this->cur_page === 0)) {
$this->cur_page = $base_page;
} else {
// Make sure we're using integers for comparisons later.
$this->cur_page = (int) $this->cur_page;
}
// Is the page number beyond the result range?
// If so, we show the last page.
if ($this->use_page_numbers) {
if ($this->cur_page > $num_pages) {
$this->cur_page = $num_pages;
}
} elseif ($this->cur_page > $this->total_rows) {
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
// If we're using offset instead of page numbers, convert it
// to a page number, so we can generate the surrounding number links.
if (!$this->use_page_numbers) {
$this->cur_page = (int) floor(($this->cur_page / $this->per_page) + 1);
}
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with.
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// And here we go...
$output = '';
// Render the "First" link.
if ($this->first_link !== FALSE && $this->cur_page > ($this->num_links + 1 + !$this->num_links)) {
// Take the general parameters, and squeeze this pagination-page attr in for JS frameworks.
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, 1);
$output .= $this->first_tag_open . '<a href="' . $first_url . '"' . $attributes . $this->_attr_rel('start') . '>'
. $this->first_link . '</a>' . $this->first_tag_close;
}
// Render the "Previous" link.
//if ($this->prev_link !== FALSE && $this->cur_page !== 1)
if ($this->prev_link !== FALSE) {//REMOVED $this->cur_page !== 1
$i = ($this->use_page_numbers) ? $uri_page_number - 1 : $uri_page_number - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, ($this->cur_page - 1));
if ($i === $base_page || $this->cur_page == 1) {//ADDED $this->cur_page == 1
// First page
$output .= $this->prev_tag_open . '<a href="' . $first_url . '"' . $attributes . $this->_attr_rel('prev') . '>'
. $this->prev_link . '</a>' . $this->prev_tag_close;
} else {
$append = $this->prefix . $i . $this->suffix;
$output .= $this->prev_tag_open . '<a href="' . $base_url . $append . '"' . $attributes . $this->_attr_rel('prev') . '>'
. $this->prev_link . '</a>' . $this->prev_tag_close;
}
}
// Render the pages
if ($this->display_pages !== FALSE) {
// Write the digit links
for ($loop = $start - 1; $loop <= $end; $loop++) {
$i = ($this->use_page_numbers) ? $loop : ($loop * $this->per_page) - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $loop);
if ($i >= $base_page) {
if ($this->cur_page === $loop) {
// Current page
$output .= $this->cur_tag_open . $loop . $this->cur_tag_close;
} elseif ($i === $base_page) {
// First page
$output .= $this->num_tag_open . '<a href="' . $first_url . '"' . $attributes . $this->_attr_rel('start') . '>'
. $loop . '</a>' . $this->num_tag_close;
} else {
$append = $this->prefix . $i . $this->suffix;
$output .= $this->num_tag_open . '<a href="' . $base_url . $append . '"' . $attributes . '>'
. $loop . '</a>' . $this->num_tag_close;
}
}
}
}
// Render the "next" link
//if ($this->next_link !== FALSE && $this->cur_page < $num_pages)
if ($this->next_link !== FALSE) {//REMOVED $this->cur_page < $num_pages
$i = ($this->use_page_numbers) ? $this->cur_page + 1 : $this->cur_page * $this->per_page;
if($this->cur_page == $num_pages){//WHEN LAST LINK
$i = $num_pages;
}
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $this->cur_page + 1);
$output .= $this->next_tag_open . '<a href="' . $base_url . $this->prefix . $i . $this->suffix . '"' . $attributes
. $this->_attr_rel('next') . '>' . $this->next_link . '</a>' . $this->next_tag_close;
}
// Render the "Last" link
if ($this->last_link !== FALSE && ($this->cur_page + $this->num_links + !$this->num_links) < $num_pages) {
$i = ($this->use_page_numbers) ? $num_pages : ($num_pages * $this->per_page) - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $num_pages);
$output .= $this->last_tag_open . '<a href="' . $base_url . $this->prefix . $i . $this->suffix . '"' . $attributes . '>'
. $this->last_link . '</a>' . $this->last_tag_close;
}
$output = preg_replace('#([^:"])//+#', '\\1/', $output);
return $this->full_tag_open . $output . $this->full_tag_close;
}
}
Just removed 2 condition
$this->cur_page !== 1 (This is below // Render the "Previous" link COMMENT)
$this->cur_page < $num_pages (This is below // Render the "next" link COMMENT)
Added 2 condition
if ($i === $base_page){... changed this as if ($i === $base_page || $this->cur_page == 1) {...
Added this inside if ($this->next_link !== FALSE) {... condition
if($this->cur_page == $num_pages){
$i = $num_pages;
}
None you have to do except putting this file in libraries directory and now your << and >> links will show always even you may change it in config as normal configuration

Well, you'll have to modify the create_links of the Pagination class. What I'd do it's extending the system/libraries/Pagination.php class with a MY_Pagination.php, so you override the behaviour and you can modify it accordingly to your preferences.
By the way, checking the class, I think you should look into lines 563 on:
// Render the "First" link.
if ($this->first_link !== FALSE && $this->cur_page > ($this->num_links + 1 + ! $this->num_links))
{
// Take the general parameters, and squeeze this pagination-page attr in for JS frameworks.
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, 1);
$output .= $this->first_tag_open.'<a href="'.$first_url.'"'.$attributes.$this->_attr_rel('start').'>'
.$this->first_link.'</a>'.$this->first_tag_close;
}
You'll have to take care of the if condition to always render the link.

Related

Magento 1.9 change custom option value depending on stock number

I have custom code that determines if a custom code value exists and if it does to select this option over the default sort order option in the product config.
What I am wanting to do is further add logic that if the product sku starts with "F" then it will show the default sort order value for that product.
The custom code is in this file..
app\code\local\Mage\Catalog\Block\Product\View\Options\Type\Select.php
Here is the code in question
// Set Default for the following cases:
// Ring Size for Men = T, Women = M
// Price for Custom Option is $0 and is the last, unless defaulted by Men or Women.
// if ($_value->getTitle() == 'M' && $isFemale) {
// $select->setValue($_value->getOptionTypeId());
// }
// else if ($_value->getTitle() == 'T' && $isMale) {
// $select->setValue($_value->getOptionTypeId());
// }
// else if ($_value->getPrice() == 0.0000 && $hasNoPrice && !$isFemale && !$isMale) {
// $select->setValue($_value->getOptionTypeId());
// }
if ($_value->getTitle() == 'M') {
$select->setValue($_value->getOptionTypeId());
}
else if ($_value->getTitle() == 'T') {
$select->setValue($_value->getOptionTypeId());
}
}
This code is ok as is.. but what I am wanting to add to the statements is that if the Stock code starts with 'F' then assign the default value.
something like
if ($sku_code == 'F') {
$select->setValue($configValue);
}
where this will show the default sort order value for the option..
I just cant seem to get this working.
Any help coding this and you get instant kudos and good Karma!
cheers
update Here is full code from Select.php
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* #category Mage
* #package Mage_Catalog
* #copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com)
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Product options text type block
*
* #category Mage
* #package Mage_Catalog
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_Catalog_Block_Product_View_Options_Type_Select
extends Mage_Catalog_Block_Product_View_Options_Abstract
{
/**
* Return html for control element
*
* #return string
*/
public function getValuesHtml()
{
$_option = $this->getOption();
$configValue = $this->getProduct()->getPreconfiguredValues()->getData('options/' . $_option->getId());
$store = $this->getProduct()->getStore();
if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_DROP_DOWN
|| $_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_MULTIPLE) {
$require = ($_option->getIsRequire()) ? ' required-entry' : '';
$extraParams = '';
$select = $this->getLayout()->createBlock('core/html_select')
->setData(array(
'id' => 'select_'.$_option->getId(),
'class' => $require.' product-custom-option'
));
if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_DROP_DOWN) {
$select->setName('options['.$_option->getid().']');
// ->addOption('', $this->__('Please Select'));
} else {
$select->setName('options['.$_option->getid().'][]');
$select->setClass('multiselect'.$require.' product-custom-option');
}
// This is a very specific case for Ring Size
// $isMale = $isFemale = $hasNoPrice = false;
// foreach ($_option->getValues() as $_value) {
// if ($_value->getTitle() == 'I' && $_value->getPrice() == 0.0000) {
// $isFemale = true;
// }
// else if ($_value->getTitle() == 'M' && $_value->getPrice() == 0.0000) {
// $isMale = true;
// }
// if ($_value->getPrice() == 0.0000) {
// $hasNoPrice = true;
// }
// }
foreach ($_option->getValues() as $_value) {
$priceStr = $this->_formatPrice(array(
'is_percent' => ($_value->getPriceType() == 'percent'),
'pricing_value' => $_value->getPrice(($_value->getPriceType() == 'percent'))
), false);
$select->addOption(
$_value->getOptionTypeId(),
$_value->getTitle() . ' ' . $priceStr . '',
array('price' => $this->helper('core')->currencyByStore($_value->getPrice(true), $store, false))
);
// Set Default for the following cases:
// Ring Size for Men = T, Women = M
// Price for Custom Option is $0 and is the last, unless defaulted by Men or Women.
// if ($_value->getTitle() == 'M' && $isFemale) {
// $select->setValue($_value->getOptionTypeId());
// }
// else if ($_value->getTitle() == 'T' && $isMale) {
// $select->setValue($_value->getOptionTypeId());
// }
// else if ($_value->getPrice() == 0.0000 && $hasNoPrice && !$isFemale && !$isMale) {
// $select->setValue($_value->getOptionTypeId());
// }
//not sure about this line
if ($sku_code[0] == 'F') {
$select->setValue($configValue);
}
else if ($_value->getTitle() == 'M') {
$select->setValue($_value->getOptionTypeId());
}
else if ($_value->getTitle() == 'T') {
$select->setValue($_value->getOptionTypeId());
}
}
if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_MULTIPLE) {
$extraParams = ' multiple="multiple"';
}
if (!$this->getSkipJsReloadPrice()) {
$extraParams .= ' onchange="opConfig.reloadPrice()"';
}
$select->setExtraParams($extraParams);
if ($configValue) {
$select->setValue($configValue);
}
return $select->getHtml();
}
if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_RADIO
|| $_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_CHECKBOX
) {
$selectHtml = '<ul id="options-'.$_option->getId().'-list" class="options-list">';
$require = ($_option->getIsRequire()) ? ' validate-one-required-by-name' : '';
$arraySign = '';
switch ($_option->getType()) {
case Mage_Catalog_Model_Product_Option::OPTION_TYPE_RADIO:
$type = 'radio';
$class = 'radio';
if (!$_option->getIsRequire()) {
$selectHtml .= '<li><input type="radio" id="options_' . $_option->getId() . '" class="'
. $class . ' product-custom-option" name="options[' . $_option->getId() . ']"'
. ($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"')
. ' value="" checked="checked" /><span class="label"><label for="options_'
. $_option->getId() . '">' . $this->__('None') . '</label></span></li>';
}
break;
case Mage_Catalog_Model_Product_Option::OPTION_TYPE_CHECKBOX:
$type = 'checkbox';
$class = 'checkbox';
$arraySign = '[]';
break;
}
$count = 1;
foreach ($_option->getValues() as $_value) {
$count++;
$priceStr = $this->_formatPrice(array(
'is_percent' => ($_value->getPriceType() == 'percent'),
'pricing_value' => $_value->getPrice($_value->getPriceType() == 'percent')
));
$htmlValue = $_value->getOptionTypeId();
if ($arraySign) {
$checked = (is_array($configValue) && in_array($htmlValue, $configValue)) ? 'checked' : '';
} else {
$checked = $configValue == $htmlValue ? 'checked' : '';
}
$selectHtml .= '<li>' . '<input type="' . $type . '" class="' . $class . ' ' . $require
. ' product-custom-option"'
. ($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"')
. ' name="options[' . $_option->getId() . ']' . $arraySign . '" id="options_' . $_option->getId()
. '_' . $count . '" value="' . $htmlValue . '" ' . $checked . ' price="'
. $this->helper('core')->currencyByStore($_value->getPrice(true), $store, false) . '" />'
. '<span class="label"><label for="options_' . $_option->getId() . '_' . $count . '">'
. $_value->getTitle() . ' ' . $priceStr . '</label></span>';
if ($_option->getIsRequire()) {
$selectHtml .= '<script type="text/javascript">' . '$(\'options_' . $_option->getId() . '_'
. $count . '\').advaiceContainer = \'options-' . $_option->getId() . '-container\';'
. '$(\'options_' . $_option->getId() . '_' . $count
. '\').callbackFunction = \'validateOptionsCallback\';' . '</script>';
}
$selectHtml .= '</li>';
}
$selectHtml .= '</ul>';
return $selectHtml;
}
}
}
maybe I don't understand right but you want to see if the sku_code starts with "f"?
EDIT:
if ($sku_code == 'F') {
$select->setValue($configValue);
}
Try:
if (strpos($sku_code, 'F') === 0) {
$select->setValue($configValue);
}
Or perhaps:
if (substr($sku_code, 0, 1) === 'F') { $select->setValue($configValue); }
Hope it helps :)

How to properly generate URL with more then one argument

How to generate URL in my current code, so I can pass the values to my directions function.
This is my code for displaying markers on map for each company:
$n = 0;
foreach ($firm as $f) {
if ($f->active == 1 && in_array($f->skd_n, $dejavnost) && $f->lat != 0) {
$lat_f = $f->lat;
$lng_f = $f->lng;
$distance = (($this->distance($lat, $lng, $lat_f, $lng_f)) * 1000);
if ($distance <= $rad && $n <= 199) {
$marker = array();
$marker['position'] = "$lat_f, $lng_f";
if ($f->phone != 0) {
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '<br/>' .
'<div class="phone_icon"></div>' .
"$f->phone" . '<br/>' .
//generate URL with 4 arguments
'DIRECTION' .
'</div><br/>';
}else{
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '</div>';
}
$marker['animation'] = 'DROP';
$marker['zIndex'] = '0';
$marker['icon'] = '../images/pin-map-red.png';
$this->googlemaps->add_marker($marker);
$n++;
}
}
}
I want to add anchor to next function, where question marks are and use variables (coordinates) as arguments:
function direction($lat, $lng, $lat_f, $lng_f){
$config['places'] = TRUE;
$config['placesAutocompleteInputID'] = 'event_location';
$config['placesAutocompleteBoundsMap'] = TRUE;
$config['zoom'] = 'auto';
$config['center'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = "$lat, $lng";
$config['directionsEnd'] = "$lat_f, $lng_f";
$config['directionsDivID'] = 'directions';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('header', $data);
$this->load->view('domov_view', $data);
$this->load->view('footer');
}
How can I use values in second function (direction) from first?
Thank you!
You could pass the arguments in url and fetch them inside your direction method via $_GET method
Example:
You could generate link like that
DIRECTION
So your function would look like this:
$n = 0;
foreach ($firm as $f) {
if ($f->active == 1 && in_array($f->skd_n, $dejavnost) && $f->lat != 0) {
$lat_f = $f->lat;
$lng_f = $f->lng;
$distance = (($this->distance($lat, $lng, $lat_f, $lng_f)) * 1000);
if ($distance <= $rad && $n <= 199) {
$marker = array();
$marker['position'] = "$lat_f, $lng_f";
if ($f->phone != 0) {
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '<br/>' .
'<div class="phone_icon"></div>' .
"$f->phone" . '<br/>' .
'DIRECTION' .
'</div><br/>';
}else{
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '</div>';
}
$marker['animation'] = 'DROP';
$marker['zIndex'] = '0';
$marker['icon'] = '../images/pin-map-red.png';
$this->googlemaps->add_marker($marker);
$n++;
}
}
}
And fetch them this way in directions function
function direction(){
$lat = $this->input->get('lat');
$lng = $this->input->get('lng');
$lat_f = $this->input->get('lat_f');
$lng_f = $this->input->get('lng_f');
$config['places'] = TRUE;
$config['placesAutocompleteInputID'] = 'event_location';
$config['placesAutocompleteBoundsMap'] = TRUE;
$config['zoom'] = 'auto';
$config['center'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = "$lat, $lng";
$config['directionsEnd'] = "$lat_f, $lng_f";
$config['directionsDivID'] = 'directions';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('header', $data);
$this->load->view('domov_view', $data);
$this->load->view('footer');
}
P.S.: If you are sending langitude and longitude via url you will probably have problems with sending disallowed chars via url (dot(.)).
You can configure allowed url chars in config file
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_=+-'
You can extend url helper. Add function some:
create_url('controller/action', [
'getParam1' => 'value1',
'getParam2' => 'value2',
'getParam3' => 'value3',
]);
And it generate http://base.url/controller/action?getParam1=value&getParam2=value2&getParam3=value3
or use
http://www.codeigniter.com/userguide2/libraries/uri.html
create link $this->uri->assoc_to_uri()
parse link $this->uri->uri_to_assoc()

Like Query Is Not Working properly

In Code igniter Model I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
public function fetchdeal_products($id) {
$this->db->select('*');
$this->db->from('products');
$q = $this->db->like("name", $id);
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
//Controller
function ajaxdealcategorydata($id = NULL) {
$this->sma->checkPermissions('index');
$id = $this->input->get('id');
$subcategories = $this->pos_model->getdealcategory($id);
$scats = '';
foreach ($subcategories as $category) {
$scats .= "<button id=\"subcategory-" . $category->id . "\" type=\"button\" value='" . $category->id . "' class=\"btn-prni subcategory\" ><img src=\"assets/uploads/thumbs/" . ($category->image ? $category->image : 'no_image.png') . "\" style='width:" . $this->Settings->twidth . "px;height:" . $this->Settings->theight . "px;' class='img-rounded img-thumbnail' /><span>" . $category->name . "</span></button>";
}
$products = $this->ajaxdealproducts($id);
if (!($tcp = $this->pos_model->products_count($id))) {
$tcp = 0;
}
echo json_encode(array('products' => $products, 'subcategories' => $scats, 'tcp' => $tcp));
}
I am using like query to fetch all the products having first name rice which is not working controller while using get_where('name') it works fine.
function ajaxdealproducts() {
$this->sma->checkPermissions('index');
if ($this->input->get('id') ) {
$id = $this->input->get('id');
} else {
$category_id = $this->pos_settings->default_category;
}
if ($this->input->get('subcategory_id')) {
$subcategory_id = $this->input->get('subcategory_id');
} else {
$subcategory_id = NULL;
}
if ($this->input->get('per_page') == 'n') {
$page = 0;
} else {
$page = $this->input->get('per_page');
}
$this->load->library("pagination");
$config = array();
$config["base_url"] = base_url() . "pos/ajaxdealproducts";
$config["total_rows"] = $subcategory_id ? $this->pos_model- >products_count($id, $subcategory_id) : $this->pos_model->products_count($id);
$config["per_page"] = $this->pos_settings->pro_limit;
$config['prev_link'] = FALSE;
$config['next_link'] = FALSE;
$config['display_pages'] = FALSE;
$config['first_link'] = FALSE;
$config['last_link'] = FALSE;
$this->pagination->initialize($config);
$products = $this->pos_model->fetchdeal_products($id, $config["per_page"], $page);
$pro = 1;
$prods = '<div>';
foreach ($products as $product) {
$count = $product->id;
if ($count < 10) {
$count = "0" . ($count / 100) * 100;
}
if ($category_id < 10) {
$category_id = "0" . ($category_id / 100) * 100;
}
$prods .= "<button id=\"product-" . $category_id . $count . "\" type=\"button\" value='" . $product->code . "' title=\"" . $product->name . "\" class=\"btn-prni btn-" . $this->pos_settings->product_button_color . " product pos-tip\" data-container=\"body\"><img src=\"" . base_url() . "assets/uploads/thumbs/" . $product->image . "\" alt=\"" . $product->name . "\" style='width:" . $this->Settings->twidth . "px;height:" . $this->Settings->theight . "px;' class='img-rounded' /><span>" . character_limiter($product->name, 15) . "</span></button>";
$pro++;
}
$prods .= "</div>";
if ($this->input->get('per_page')) {
echo $prods;
} else {
return $prods;
}
}
The database LIKE function only creates a LIKE in the SQL statement. You'll still need to call the GET mothod afterwards; Like this;
$this->db->like('name', $id);
$q = $this->db->get();
You are using $this->db_like() incorrectly.
$this->db->like('title', 'match');
// Produces: WHERE title LIKE '%match%'
(from documentation)
In your case the usage would be
$this->db->like('name', 'rice')
More info
public function fetchdeal_products($id)
{
$query = $this->db->query("Select products.* From products Where (products.name Like '%$id%')");
$result = $query->result_array();
return $result;
}
you have to write it as bellow.
public function fetchdeal_products($id) {
$this->db->like("name", $id);
$q = $this->db->get('products');
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}

How to list products in Magento Menu

Like this question:
Magento: HOW-TO add active products in a drop-down in Main Navigation Menu
...I want to list the products from a category in the main menu. I have attempted to use the code provided but it's still not working. I'm using Magento ver. 1.7.0.2 so I think this may be the issue.
Any help would be appreciated.
I had the same problem and after some hours I have a solution now. I'm using Magento 1.9.1 and I also needed to edit the Topmenu.php file. Probably it's not the best way to do it, but it works. I tried to comment everything, so maybe it's easier to understand.
I changed '_getHtml' function to include the products and to change classes of 'li'-tags, if necessary:
protected function _getHtml(Varien_Data_Tree_Node $menuTree, $childrenWrapClass, $correctClasses = 0)
{
$html = '';
$children = $menuTree->getChildren();
$parentLevel = $menuTree->getLevel();
$childLevel = is_null($parentLevel) ? 0 : $parentLevel + 1;
$counter = 1;
$childrenCount = $children->count();
$parentPositionClass = $menuTree->getPositionClass();
$itemPositionClassPrefix = $parentPositionClass ? $parentPositionClass . '-' : 'nav-';
foreach ($children as $child) {
$child->setLevel($childLevel);
$child->setIsFirst($counter == 1);
$child->setIsLast($counter == $childrenCount);
$child->setPositionClass($itemPositionClassPrefix . $counter);
$outermostClassCode = '';
$outermostClass = $menuTree->getOutermostClass();
if ($childLevel == 0 && $outermostClass) {
$outermostClassCode = ' class="' . $outermostClass . '" ';
$child->setClass($outermostClass);
}
// avoid 'last'-class if there are products after categories
$renderedAttributes = $this->_getRenderedMenuItemAttributes($child);
if($correctClasses = 1) {
$renderedAttributes = str_replace(' last', '', $renderedAttributes);
}
// add 'category' class to category elements
$renderedAttributes = str_replace('class="', 'class="type-category ', $renderedAttributes);
$html .= '<li ' . $renderedAttributes . '>';
$html .= '<a href="' . $child->getUrl() . '" ' . $outermostClassCode . '><span>' . $this->escapeHtml($child->getName()) . '</span></a>';
// check if there are more categories or products inside
$hasProducts = $this->hasProducts($child);
if ($child->hasChildren() || $hasProducts) {
if (!empty($childrenWrapClass)) {
$html .= '<div class="' . $childrenWrapClass . '">';
}
// build ul-wrapper
$html .= '<ul class="level' . $childLevel . '">';
// if categories and products are in this category
if($child->hasChildren() && $hasProducts) {
$correctClasses = 1;
$html .= $this->_getHtml($child, $childrenWrapClass, $correctClasses);
$html .= $this->getProducts($child, $childLevel, $correctClasses);
// if only categories are in this category
} elseif($child->hasChildren()) {
$html .= $this->_getHtml($child, $childrenWrapClass);
// if only products are in this category
} elseif($hasProducts) {
$html .= $this->getProducts($child, $childLevel);
}
$html .= '</ul>';
if (!empty($childrenWrapClass)) {
$html .= '</div>';
}
}
$html .= '</li>';
$counter++;
}
return $html;
}
Additionally I wrote 3 new functions to process everything.
One new small function to get the product collection from current category:
// get product collection
protected function getProductCollection($child) {
// get current category
$catId = str_replace('category-node-', '', $child->getId());
$curCategory = Mage::getModel('catalog/category')->load($catId);
// get prouct collection from current category
return Mage::getResourceModel('catalog/product_collection')->addCategoryFilter($curCategory)->setOrder('position','ASC');
}
A function to check if there are any products in current category:
// check if there are products in this category
protected function hasProducts($child) {
// get number of products in current (sub-)category
$productCount = $this->getProductCollection($child)->count();
if($productCount > 0) {
return 1;
} else {
return 0;
}
}
And one function to build the html for the product list items:
// get product html
protected function getProducts($child, $level, $correctClasses = 0) {
$productCollection = $this->getProductCollection($child);
// set product counter
$p = 1;
// get number of products in current (sub-)category
$productCount = $productCollection->count();
$pChild = '';
if ($productCount > 0) {
$level++;
foreach ($productCollection as $product) {
// get current product in loop
$curProduct = Mage::getModel('catalog/product')->load($product->getId());
// check if current product in loop is activated
if ($curProduct->getStatus()) {
// build list-item with classes
$pChild .= '<li';
$pChild .= ' class="type-product level'.$level;
if ($p == 1 && $correctClasses == 0) {
$pChild .= ' first';
}
if ($p == $productCount) {
$pChild .= ' last';
}
$pChild .= '">'."\n";
$pChild .= ' '.$this->htmlEscape($curProduct->getName()).''."\n";
$pChild .= '</li>';
// increment product counter
$p++;
}
}
}
return $pChild;
}
Hopefully it helps someone! If someone has suggestions to write it more clean or to add some functionality, post something or comment it! :)

CodeIgniter: pagination doesn't have question mark?

The code below generates pagination using query strings. However, there is no leading ?. So, I get something like this: http://localhost/index.php/search/&limit=10. Any ideas why?
this->load->library('pagination');
$config = array();
$config['base_url'] = 'http://localhost/index.php/search/';
$config['total_rows'] = 200;
$config['per_page'] = 10;
$config['num_links'] = 4;
$config['full_tag_open'] = '<ol>';
$config['full_tag_close'] = '</ol>';
$config['first_link'] = 'First';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['next_link'] = 'Next';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['prev_link'] = 'Previous';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active">';
$config['cur_tag_close'] = '</li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$this->pagination->initialize($config);
echo ($this->pagination->create_links());
EDIT 1:
http://codeigniter.com/forums/viewthread/161263/
EDIT 2:
The docs seem to suggest that what I did should work: http://codeigniter.com/user_guide/libraries/pagination.html
$config['page_query_string'] = TRUE;
By default, the pagination library assume you are using URI Segments, and constructs your links something like
http://example.com/index.php/test/page/20
If you have $config['enable_query_strings'] set to TRUE your links will automatically be re-written using Query Strings. This option can also be explictly set. Using $config['page_query_string'] set to TRUE, the pagination link will become.
http://example.com/index.php?c=test&m=page&per_page=20
I've run into this myself. When using query strings, CodeIgniter has to assume you have other query string parameters (BUT, CI assumes you're using query string parameters to map your controller and method...). I like using query string for stuff like filtering results and such, while still using the basic routing options in the URI (like you).
I've had to live with the ?& personally, but I suppose you could extend the Pagination library like so (long function, sorry):
class MY_Pagination extends CI_Pagination {
function create_links()
{
// If our item count or per-page total is zero there is no need to continue.
if ($this->total_rows == 0 OR $this->per_page == 0)
{
return '';
}
// Calculate the total number of pages
$num_pages = ceil($this->total_rows / $this->per_page);
// Is there only one page? Hm... nothing more to do here then.
if ($num_pages == 1)
{
return '';
}
// Determine the current page number.
$CI =& get_instance();
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
if ($CI->input->get($this->query_string_segment) != 0)
{
$this->cur_page = $CI->input->get($this->query_string_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
else
{
if ($CI->uri->segment($this->uri_segment) != 0)
{
$this->cur_page = $CI->uri->segment($this->uri_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
$this->num_links = (int)$this->num_links;
if ($this->num_links < 1)
{
show_error('Your number of links must be a positive number.');
}
if ( ! is_numeric($this->cur_page))
{
$this->cur_page = 0;
}
// Is the page number beyond the result range?
// If so we show the last page
if ($this->cur_page > $this->total_rows)
{
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// Is pagination being used over GET or POST? If get, add a per_page query
// string. If post, add a trailing slash to the base URL if needed
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
$this->base_url = str_replace('?&', '?', rtrim($this->base_url).'&'.$this->query_string_segment.'=');
}
else
{
$this->base_url = rtrim($this->base_url, '/') .'/';
}
// And here we go...
$output = '';
// Render the "First" link
if ($this->first_link !== FALSE AND $this->cur_page > ($this->num_links + 1))
{
$first_url = ($this->first_url == '') ? $this->base_url : $this->first_url;
$output .= $this->first_tag_open.'<a '.$this->anchor_class.'href="'.$first_url.'">'.$this->first_link.'</a>'.$this->first_tag_close;
}
// Render the "previous" link
if ($this->prev_link !== FALSE AND $this->cur_page != 1)
{
$i = $uri_page_number - $this->per_page;
if ($i == 0 && $this->first_url != '')
{
$output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
else
{
$i = ($i == 0) ? '' : $this->prefix.$i.$this->suffix;
$output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$i.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
}
// Render the pages
if ($this->display_pages !== FALSE)
{
// Write the digit links
for ($loop = $start -1; $loop <= $end; $loop++)
{
$i = ($loop * $this->per_page) - $this->per_page;
if ($i >= 0)
{
if ($this->cur_page == $loop)
{
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
}
else
{
$n = ($i == 0) ? '' : $i;
if ($n == '' && $this->first_url != '')
{
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$loop.'</a>'.$this->num_tag_close;
}
else
{
$n = ($n == '') ? '' : $this->prefix.$n.$this->suffix;
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$n.'">'.$loop.'</a>'.$this->num_tag_close;
}
}
}
}
}
// Render the "next" link
if ($this->next_link !== FALSE AND $this->cur_page < $num_pages)
{
$output .= $this->next_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.($this->cur_page * $this->per_page).$this->suffix.'">'.$this->next_link.'</a>'.$this->next_tag_close;
}
// Render the "Last" link
if ($this->last_link !== FALSE AND ($this->cur_page + $this->num_links) < $num_pages)
{
$i = (($num_pages * $this->per_page) - $this->per_page);
$output .= $this->last_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.$i.$this->suffix.'">'.$this->last_link.'</a>'.$this->last_tag_close;
}
// Kill double slashes. Note: Sometimes we can end up with a double slash
// in the penultimate link so we'll kill all double slashes.
$output = preg_replace("#([^:])//+#", "\\1/", $output);
// Add the wrapper HTML if exists
$output = $this->full_tag_open.$output.$this->full_tag_close;
return $output;
}
}

Resources