Prestashop module tab slider random product - random

This is Tab category slider module of Prestashop CMS, it shows last added productes, i need to show random products.
I will add more info if it will be needed
sry for my bad English.
Thanks for help guys.
class postabcateslider1 extends Module {
private $spacer_size = '5';
private $_postErrors = array();
private $_html= null;
public function __construct() {
$this->name = 'postabcateslider1';
$this->tab = 'front_office_features';
$this->version = '1.5';
$this->author = 'posthemes';
$this->displayName = $this->l('Category Tabs Slider 1');
$this->description = $this->l('Category Tabs Slider 1');
parent :: __construct();
}
public function install() {
Configuration::updateValue($this->name . '_p_on_row', 4);
Configuration::updateValue($this->name . '_p_limit', 30);
Configuration::updateValue($this->name . '_tab_effect', 'wiggle');
Configuration::updateValue($this->name . '_p_on_row', 4);
Configuration::updateValue($this->name . '_p_width', 150);
Configuration::updateValue($this->name . '_p_height', 200);
Configuration::updateValue($this->name . '_min_item', 1);
Configuration::updateValue($this->name . '_max_item', 5);
Configuration::updateValue($this->name . '_speed_slide', 3000);
Configuration::updateValue($this->name . '_a_speed', 500);
Configuration::updateValue($this->name . '_show_arrow', 0);
Configuration::updateValue($this->name . '_show_ctr', 0);
$arrayDefault = array('CAT3','CAT4','CAT5');
$cateDefault = implode(',',$arrayDefault);
Configuration::updateGlobalValue($this->name . '_list_cate',$cateDefault);
return parent :: install()
&& $this->registerHook('top')
/* && $this->registerHook('displayHome') */
&& $this->registerHook('blockPosition2')
//&& $this->registerHook('displayHome')
&& $this->registerHook('header')
&& $this->registerHook('actionOrderStatusPostUpdate')
&& $this->registerHook('addproduct')
&& $this->registerHook('updateproduct')
&& $this->registerHook('deleteproduct');
}
public function uninstall() {
Configuration::deleteByName($this->name . '_list_cate');
$this->_clearCache('postabcateslider1.tpl');
return parent::uninstall();
}
public function psversion() {
$version=_PS_VERSION_;
$exp=$explode=explode(".",$version);
return $exp[1];
}
public function hookHeader($params){
// if ($this->psversion()==5){
// $this->context->controller->addCSS(($this->_path).'postabcateslider.css', 'all');
// $this->context->controller->addCSS(($this->_path).'animate.delay.css', 'all');
// $this->context->controller->addCSS(($this->_path).'animate.min.css', 'all');
// } else {
// Tools::addCSS(($this->_path).'postabcateslider.css');
// Tools::addCSS(($this->_path).'animate.delay.css');
// Tools::addCSS(($this->_path).'animate.min.css');
// }
}
public function hookblockPosition2($params) {
$nb = Configuration::get($this->name . '_p_limit');
$product_on_row = Configuration::get($this->name . '_p_on_row');
$arrayCategory = array();
$catSelected = Configuration::get($this->name . '_list_cate');
$cateArray = explode(',', $catSelected);
$id_lang =(int) Context::getContext()->language->id;
$id_shop = (int) Context::getContext()->shop->id;
$arrayProductCate = array();
foreach($cateArray as $id_category) {
$id_category = str_replace('CAT','',$id_category);
$category = new Category((int) $id_category, (int) $id_lang, (int) $id_shop);
$categoryProducts = $category->getProducts($this->context->language->id, 0, ($nb ? $nb : 5),'date_add','DESC');
if($categoryProducts) {
$arrayProductCate[] = array('id' => $id_category, 'name'=> $category->name, 'product' => $categoryProducts);
}
}
$options = array(
'p_width' => Configuration::get($this->name . '_p_width'),
'p_height' => Configuration::get($this->name . '_p_height'),
'speed_slide' => Configuration::get($this->name . '_speed_slide'),
'a_speed' => Configuration::get($this->name . '_a_speed'),
'show_des' => Configuration::get($this->name . '_show_des'),
'show_arrow' => Configuration::get($this->name . '_show_arrow'),
'show_ctr' => Configuration::get($this->name . '_show_ctr'),
'min_item' => Configuration::get($this->name . '_min_item'),
'max_item' => Configuration::get($this->name . '_max_item'), 'show_price' => Configuration::get($this->name . '_show_price'),
);
$this->context->smarty->assign('slideOptions', $options);
$this->smarty->assign(array(
'productCates' => $arrayProductCate,
'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'),
'homeSize' => Image::getSize(ImageType::getFormatedName('home')),
'product_on_row' => $product_on_row,
'tab_effect' => Configuration::get($this->name . '_tab_effect'),
'title' => Configuration::get($this->name . '_title'),
));
return $this->display(__FILE__, 'postabcateslider1.tpl');
}
public function getContent() {
$output = '<h2>' . $this->displayName . '</h2>';
if (Tools::isSubmit('submitPosTabCate')) {
if (!sizeof($this->_postErrors))
$this->_postProcess();
else {
foreach ($this->_postErrors AS $err) {
$this->_html .= '<div class="alert error">' . $err . '</div>';
}
}
}
return $output . $this->_displayForm();
}
public function getSelectOptionsHtml($options = NULL, $name = NULL, $selected = NULL) {
$html = "";
$html .='<select name =' . $name . ' style="width:130px">';
if (count($options) > 0) {
foreach ($options as $key => $val) {
if (trim($key) == trim($selected)) {
$html .='<option value=' . $key . ' selected="selected">' . $val . '</option>';
} else {
$html .='<option value=' . $key . '>' . $val . '</option>';
}
}
}
$html .= '</select>';
return $html;
}
private function _postProcess() {
Configuration::updateValue($this->name . '_list_cate', implode(',', Tools::getValue('list_cate')));
Configuration::updateValue($this->name . '_p_on_row', Tools::getValue('p_on_row'));
Configuration::updateValue($this->name . '_p_limit', Tools::getValue('p_limit'));
Configuration::updateValue($this->name . '_tab_effect', Tools::getValue('tab_effect'));
Configuration::updateValue($this->name . '_title', Tools::getValue('title'));
Configuration::updateValue($this->name . '_p_height', Tools::getValue('p_height'));
Configuration::updateValue($this->name . '_p_width', Tools::getValue('p_width'));
Configuration::updateValue($this->name . '_p_limit', Tools::getValue('p_limit'));
Configuration::updateValue($this->name . '_speed_slide', Tools::getValue('speed_slide'));
Configuration::updateValue($this->name . '_a_speed', Tools::getValue('a_speed'));
Configuration::updateValue($this->name . '_show_arrow', Tools::getValue('show_arrow'));
Configuration::updateValue($this->name . '_show_ctr', Tools::getValue('show_ctr'));
Configuration::updateValue($this->name . '_min_item', Tools::getValue('min_item'));
Configuration::updateValue($this->name . '_max_item', Tools::getValue('max_item'));
$this->_html .= '<div class="conf confirm">' . $this->l('Settings updated') . '</div>';
}
private function _displayForm(){
$spacer = str_repeat(' ', $this->spacer_size);
$tabEffect = array();
$tabEffect = array(
'none' => 'None',
'hinge' => 'Hinge',
'flash' => 'Flash',
'shake' => 'Shake',
'bounce' => 'Bounce',
'tada' => 'Tada' ,
'swing' => 'Swing',
'wobble' => 'Wobble',
'pulse' => 'Pulse',
'flip' => 'Flip',
'flipInX' => 'FlipInX',
'flipInY' => 'FlipInY',
'fadeIn' => 'FadeIn',
'bounceInUp' => 'BounceInUp',
'fadeInLeft' => 'FadeInLeft',
'rollIn' => 'RollIn',
'lightSpeedIn' => 'LightSpeedIn',
'wiggle' => 'Wiggle',
'rotateIn' => 'RotateIn',
'rotateInUpLeft' => 'RotateInUpLeft',
'rotateInUpRight' => 'RotateInUpRight'
);
$this->_html .= '
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<fieldset>
<legend><img src="../img/admin/cog.gif" alt="" class="middle" />' . $this->l('Settings') . '</legend>
<label>'.$this->l('Title: ').'</label>
<div class="margin-form">
<input type = "text" name="title" value ='.(Tools::getValue('title')?Tools::getValue('title'): Configuration::get($this->name.'_title')).' ></input>
</div>
<label>'.$this->l('Effect Tab: ').'</label>
<div class="margin-form">';
$this->_html .= $this->getSelectOptionsHtml($tabEffect,'tab_effect', (Tools::getValue('tab_effect') ? Tools::getValue('tab_effect') : Configuration::get($this->name . '_tab_effect')));
$this->_html .='
</div>';
$this->_html .= '<label>' . $this->l('Show Link/Label Category: ') . '</label>';
$this->_html .= '<div class="margin-form">';
$this->_html .= '<select multiple="multiple" name ="list_cate[]" style="width: 200px; height: 160px;">';
// BEGIN Categories
$id_lang = (int) Context::getContext()->language->id;
$this->getCategoryOption(1, (int) $id_lang, (int) Shop::getContextShopID());
$this->_html .= '</select>
</div>';
$this->_html .='
<label>' . $this->l('Show Next/Back control: : ') . '</label>
<div class="margin-form">';
$this->_html .= $this->getSelectOptionsHtml(array(0 => 'No', 1 => 'Yes'), 'show_arrow', (Tools::getValue('title') ? Tools::getValue('show_arrow') : Configuration::get($this->name . '_show_arrow')));
$this->_html .='
</div>
<label>' . $this->l('Show navigation control: : ') . '</label>
<div class="margin-form">';
$this->_html .= $this->getSelectOptionsHtml(array(0 => 'No', 1 => 'Yes'), 'show_ctr', (Tools::getValue('title') ? Tools::getValue('show_ctr') : Configuration::get($this->name . '_show_ctr')));
$this->_html .='
</div>
<label>'.$this->l('Products Limit: ').'</label>
<div class="margin-form">
<input type = "text" name="p_limit" value ='.(Tools::getValue('p_limit')?Tools::getValue('p_limit'): Configuration::get($this->name.'_p_limit')).' ></input>
</div>
<input type="submit" name="submitPosTabCate" value="'.$this->l('Update').'" class="button" />
</fieldset>
</form>';
return $this->_html;
}
private function getCategoryOption($id_category = 1, $id_lang = false, $id_shop = false, $recursive = true) {
$cateCurrent = Configuration::get($this->name . '_list_cate');
$cateCurrent = explode(',', $cateCurrent);
$id_lang = $id_lang ? (int)$id_lang : (int)Context::getContext()->language->id;
$category = new Category((int)$id_category, (int)$id_lang, (int)$id_shop);
if (is_null($category->id))
return;
if ($recursive)
{
$children = Category::getChildren((int)$id_category, (int)$id_lang, true, (int)$id_shop);
$spacer = str_repeat(' ', $this->spacer_size * (int)$category->level_depth);
}
$shop = (object) Shop::getShop((int)$category->getShopID());
if (in_array('CAT'.(int)$category->id, $cateCurrent)) {
$this->_html .= '<option value="CAT'.(int)$category->id.'" selected ="selected" >'.(isset($spacer) ? $spacer : '').$category->name.' ('.$shop->name.')</option>';
} else {
$this->_html .= '<option value="CAT'.(int)$category->id.'">'.(isset($spacer) ? $spacer : '').$category->name.' ('.$shop->name.')</option>';
}
if (isset($children) && count($children))
foreach ($children as $child)
$this->getCategoryOption((int)$child['id_category'], (int)$id_lang, (int)$child['id_shop']);
}
}

I find solution by myself! Thanks for dawnvote
you need to edit this code
$categoryProducts = $category->getProducts($this->context->language->id, 0, ($nb ? $nb : 5),'date_add','DESC');
if($categoryProducts) {
$arrayProductCate[] = array('id' => $id_category, 'name'=> $category->name, 'product' => $categoryProducts);
}
with it
$categoryProducts = $category->getProducts($this->context->language->id, 0, ($nb ? $nb : 5));
shuffle($categoryProducts);
if($categoryProducts) {
$arrayProductCate[] = array('id' => $id_category, 'name'=> $category->name, 'product' => $categoryProducts);
}

Related

Filter custom post with taxonomy - Add ALL button

I am setting up a custom post with a front-office display filter via taxonomy. After several hours of research and tests, I finally managed to get what I want but I still have 2 little things on which I am stuck... I would have liked to add an ALL button to re-display all my archives if we clicked on another filter before.
I also can’t add a class to my filter button when it is activated... Do you have a lead to refer me please?
Below what I did:
archive-work.php
<div id="work-filter" class="col-md-12">
<?php get_work_filters(); ?>
</div>
<div class="work-results animated fadeIn">
<?php $res = my_get_posts();
echo $res['response']; ?>
</div>
functions.php
/***************** filter work ****************/
function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', get_template_directory_uri() .
'/assets/js/work.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
$result = array();
// Script for getting posts
function ajax_filter_get_posts( $work_item ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) ||
!wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ))
die('Permission denied');
$work_item = $_POST['expertises'];
$result = json_encode(my_get_posts($work_item, true));
echo $result;
die();
}
function my_get_posts($work_item = '', $ajax = false){
// WP Query
$args = array(
'expertises' => $work_item,
'post_type' => 'work',
'posts_per_page' => -1,
);
// If taxonomy is not set, remove key from array and get all posts
if( !$work_item ) {
unset( $args['expertises'] );
}
$query = new WP_Query( $args );
$html = '';
$items = array();
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
$res = '<div class="works">'.
'<a href="'.get_permalink().'">'.
'<article class="panel panel-default" id="post-'.get_the_id().'">'.
'<div class="panel-body">'.
'<div class="panel-cover">'.
'<h3>'.get_the_title().'</h3>'.
get_the_excerpt().
'</div>'.
'<div class="imgworkarch">'.
get_the_post_thumbnail( $post = null, $size = 'archivework' ).
'</div>'.
'</div>'.
'</article>'.
'</a>' .
'</div>';
$ajax ? $items[] = $res : $html .= $res;
endwhile;
$result['response'] = $ajax ? $items : $html;
$result['status'] = 'success';
else:
$result['response'] = '<h2>No posts found</h2>';
$result['status'] = '404';
endif;
wp_reset_postdata();
return $result;
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
//Get Work Filters
function get_work_filters()
{
$work_items = get_terms('expertises');
$filters_html = false;
$count = count( $work_items );
if( $count > 0 ):
foreach( $work_items as $work_item )
{
$work_item_id = $work_item->term_id;
$work_item_name = $work_item->name;
$filters_html .= '<a href="' .
get_term_link( $work_item ) .
'" class="btn work-filter" title="' .
$work_item->slug . '">' . $work_item->name . '</a> ';
}
echo $filters_html;
endif;
}
work.js
$(document).ready(function(){
// work filters
$('.work-filter').click( function(event) {
// Prevent default action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var expertises = $(this).attr('title');
data = {
action: 'filter_posts', // function to execute
afp_nonce: afp_vars.afp_nonce, // wp_nonce
post_type: "work", // selected tag
expertises: expertises,
};
$.ajax({
type: "post",
dataType: "json",
url: afp_vars.afp_ajax_url,
data: data,
success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
// Restore div visibility
$('.work-results').fadeOut()
.queue(function(n) {
$(this).html(data.response);
n();
}).fadeIn();
},
error: function( XMLHttpRequest, textStatus, errorThrown ) {
/*console.log( MLHttpRequest );
console.log( textStatus );
console.log( errorThrown );*/
$('.work-results').fadeOut()
.queue(function(n) {
$(this).html("No items found. ");
n();
}).fadeIn();
}
});
});
});
Maybe it's too late to answer this, but I hope it helps someone.
You just have to add another button into your work-filter block with a different title like 'reset', then remove the taxonomy filter on the query in your my_get_posts when the value matches the title. Here is the code:
function my_get_posts($taxonomy = '', $ajax = false)
{
if($taxonomy != 'reset'){
$args = array(
'service' => $taxonomy,
'post_type' => 'projects',
'posts_per_page' => -1,
);
}else{
$args = array(
'post_type' => 'projects',
'posts_per_page' => -1,
);
}
if (!$taxonomy) {
unset($args['service']);
}
$query = new WP_Query($args);
$html = '';
$items = array();
if ($query->have_posts()) :
while ($query->have_posts()) :
$query->the_post();
$res = '<div class="col-lg-4">' .
'<a href="' . get_permalink() . '">' .
'<article class="panel panel-default" id="post-' . get_the_id() . '">' .
'<div class="panel-body">' .
get_the_post_thumbnail() .
'<div class="panel-cover">' .
'<h3>' . get_the_title() . '</h3>' .
get_the_content() .
'</div>' .
'</div>' .
'</article>' .
'</a>' .
'</div>';
$ajax ? $items[] = $res : $html .= $res;
endwhile;
$result['response'] = $ajax ? $items : $html;
$result['status'] = 'success';
else :
$result['response'] = '<h2>No posts found</h2>';
$result['status'] = '404';
endif;
wp_reset_postdata();
return $result;
}
function reset_all(){
echo 'All ';
}

Custom Pagination Page Count Message

On my controller I am trying to be able to display a message where it counts from 1 "Your On Page 1" etc
How ever it does not start of at 1 it starts at 0 "Your On Page 0"
$message = '';
$message .= '<p>' . sprintf('Your on page %d', ($config['total_rows']) ? (($start - 1) * $config['per_page']) + 1 : 0) . '</p>';
$message .= '<p>Total ( Pages ' . ceil($config['total_rows'] / $config['per_page']) . ' )</p>';
$data['total'] = $message;
Question: How can I make sure that it can count from 1 instead of 0 in message with out effecting the main pagination on controller
Controller
<?php
class Forum extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->model('catalog/forum/forum_model');
$this->load->library('pagination');
}
public function category() {
$this->document->set_title('Forums');
$category_id = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
if ($this->input->get('order')) {
$order = $this->input->get('order');
} else {
$order = 'asc';
}
if ($this->input->get('sort')) {
$sort = $this->input->get('sort');
} else {
$sort = 'message';
}
$url = '';
if ($this->input->get('sort')) {
$url .= '?sort=' . $this->input->get('sort');
}
if ($this->input->get('order')) {
$url .= '&order=' . $this->input->get('order');
}
$config["base_url"] = base_url('forum/category') .'/'. $category_id .'/';
$config["total_rows"] = $this->forum_model->total_category($category_id);
$config["per_page"] = 1;
$config['page_query_string'] = TRUE;
$config['reuse_query_string'] = TRUE;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] ="</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$start = ($this->input->get('per_page')) ? $this->input->get('per_page') : '';
$filter_data = array(
'limit' => $config["per_page"],
'start' => $start,
'category_id' => $category_id,
'sort' => ($this->input->get('sort')) ? $this->input->get('sort') : 'message',
'order' => ($this->input->get('order')) ? $this->input->get('order') : 'asc'
);
$data['threads'] = array();
$results = $this->forum_model->get_threads_for_forum($filter_data);
foreach ($results as $result) {
$data['threads'][] = array(
'thread_id' => $result['thread_id'],
'user_id' => $result['user_id'],
'username' => $result['username'],
'subject' => $result['subject'],
'link' => site_url('thread') . '-' . $result['thread_id'],
'total' => $this->forum_model->total_threads($result['thread_id']),
'date_created' => date('d-m-Y', strtotime($result['date_created'])),
'user_link' => site_url('user') . '-' . $result['user_id']
);
}
$data['back'] = site_url('forum');
$data['newthread'] = site_url('newthread') . '?fid=' . $category_id;
$url = '';
if ($order == 'asc') {
$url .= '&order=desc';
} else {
$url .= '&order=asc';
}
if ($this->input->get('per_page')) {
$url .= '&per_page=' . $this->input->get('per_page');
}
$data['thread_message'] = site_url('forum/category') .'/'. $category_id .'/'. '?sort=message' . $url;
$data['date_created'] = site_url('forum/category') .'/'. $category_id .'/'. '?sort=date_created' . $url;
$data['sort'] = $sort;
$data['order'] = $order;
$total_threads = $this->forum_model->get_total_threads_for_category($category_id);
$message = '';
$message .= '<p>' . sprintf('Your on page %d', ($config['total_rows']) ? (($start - 1) * $config['per_page']) + 1 : 0) . '</p>';
$message .= '<p>Total ( Pages ' . ceil($config['total_rows'] / $config['per_page']) . ' )</p>';
$data['total'] = $message;
$data['header'] = Modules::run('catalog/common/header/index');
$data['footer'] = Modules::run('catalog/common/footer/index');
$data['menu'] = Modules::run('catalog/common/menu/index');
$this->load->view('default/template/forum/forum_thread_view', $data);
}
}
It ended up being a simple fix had brain fart should of picked it up straight away.
I changed
(($start - 1) * $config['per_page']) + 1 : 0)
To
(($start - 0) * $config['per_page']) + 1 : 0)

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;
}
}

Error Message show encountered Severity: Notice Message:

On my controller for development I have added error_reporting(0); just below the opening php tag on my controller. So will not show some errors.
When go to live mode and remove or comment out the added error_reporting(0); I get a couple of errors
A PHP Error was encountered Severity: Notice Message: Undefined
variable: other_sub Filename: common/Filemanager.php
A PHP Error was encountered Severity: Notice Message: Undefined
variable: histSub Filename: common/Filemanager.php
Question: I have those variables defined not sure why errors showing?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//error_reporting(0);
class Filemanager extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->library('pagination');
$this->lang->load('admin/common/filemanager', 'english');
$this->load->model('admin/tool/model_tool_image');
}
public function index() {
$directory = FCPATH . 'image/catalog/';
$element = $this->input->get('element'); // Element
$input = $this->input->get('input'); // Target
$sub_get = $this->input->get("sub"); // Sub Folders
$end_url = '?';
$end_url .= 'input='.$input;
$end_url .= '&element='.$element;
$endHist = $end_url;
$uris = $this->uri->segment_array();
$sub_folder = "";
if ($sub_get) {
$sub_folder = $sub_get;
}
if ($sub_folder) {
$end_url .= '&sub=' .$sub_folder;
if (sizeof($uris) >3 ) {
for ($i=3; $i < sizeof($uris); $i++) {
$directory .= $uris[$i].'/';
$other_sub .= $uris[$i].'/';
}
$directory .= $sub_folder.'/';
$other_sub .= $sub_folder.'/';
} else {
$directory .= $sub_folder.'/';
$other_sub = $sub_folder.'/';
}
}
$data['images'] = array();
// Get directories
$directories = glob($directory . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
$files = glob($directory.'*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
if (!$files) {
$files = array();
}
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
$per_page = 8;
$segment = $this->input->get('per_page');
$segment += $per_page;
foreach ($images as $key => $image) {
if ($key < $segment && $key >= $segment-$per_page) {
$name = str_split(basename($image), 18);
if (is_dir($image)) {
$data['images'][] = array(
'thumb' => '',
'name' => implode(' ', $name),
'type' => 'directory',
'path' => utf8_substr($image, utf8_strlen(FCPATH .'image/')),
'href' => site_url('admin/filemanager') .'/'. utf8_substr($image, utf8_strlen(FCPATH . 'image/catalog/')),
);
} elseif (is_file($image)) {
$subDirect = 'catalog/'.$other_sub;
$data['images'][] = array(
'thumb' => $this->model_tool_image->resize(utf8_substr($image, utf8_strlen(DIR_IMAGE)), 100, 100),
'name' => implode(' ', $name),
'type' => 'image',
'path' => $subDirect.utf8_substr($image, utf8_strlen($directory)),
'href' => base_url() . 'image/' . utf8_substr($image, utf8_strlen(FCPATH . 'image/catalog/'))
);
}
}
}
$data['title'] = "Image Manager";
$data['heading_title'] = "Image Manager";
if (isset($sub_folder)) {
$data['directory'] = $this->uri->segment(3) .'/'. $this->uri->segment(4);
} else {
$data['directory'] = '';
}
if ($element) {
$data['element'] = $element;
} else {
$data['element'] = "";
}
if ($input) {
$data['target'] = $input;
} else {
$data['target'] = "";
}
$endRep = $end_url == '?' ? '' : rtrim($end_url,'&');
// Sets go to previous parent folder.
if ($other_sub) {
$arraySub = explode('/', rtrim($other_sub,'/'));
unset($arraySub[sizeof($arraySub) -1]);
$histSub = "";
foreach ($arraySub as $one) {
$histSub .= $one.'/';
}
$endHist .= "&sub=".$arraySub[sizeof($arraySub) - 1];
}
// Parent folder link
$data['parent'] = site_url('admin/filemanager') .'/'. $histSub . $endHist;
// Refesh current Page
$data['refresh'] = current_url().$endRep;
$config['base_url'] = base_url('admin/filemanager/') .'/'. $other_sub.$endRep;
$config['end_url'] = $end_url == '?' ? '' : rtrim($end_url,'&');
$config['total_rows'] = $image_total;
$config['per_page'] = $per_page;
$config['page_query_string'] = TRUE;
$config['num_links'] = "16";
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] ="</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
return $this->load->view('template/common/filemanager_view', $data);
}
}
Problem now solved I had to change a few things and make the input->get setup a lot more simple now works fine.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Filemanager extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->library('pagination');
$this->lang->load('admin/common/filemanager', 'english');
$this->load->model('admin/tool/model_tool_image');
}
public function index() {
$input_get_directory = $this->input->get('directory');
$input_get_page = $this->input->get('page');
$input_get_filter = $this->input->get('filter_name');
$input_get_target = $this->input->get('target');
$input_get_thumb = $this->input->get('thumb');
if (isset($input_get_filter)) {
$filter_name = $input_get_filter .'/';
} else {
$filter_name = null;
}
// Make sure we have the correct directory
if (isset($input_get_directory)) {
$directory = FCPATH . 'image/catalog/' . $input_get_directory;
} else {
// Do not add extra tralier slash at end /
$directory = FCPATH . 'image/catalog';
}
if (isset($input_get_page)) {
$page = $input_get_page;
} else {
$page = 1;
}
$data['images'] = array();
// Get directories
$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
$files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
if (!$files) {
$files = array();
}
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
// Split the array based on current page number and max number of items per page of 10
$images = array_splice($images, ($page - 1) * 16, 16);
foreach ($images as $image) {
$name = str_split(basename($image), 14);
if (is_dir($image)) {
$url = '';
if (isset($input_get_target)) {
$url .= '&target=' . $input_get_target;
}
if (isset($input_get_thumb)) {
$url .= '&thumb=' . $input_get_thumb;
}
$data['images'][] = array(
'thumb' => '',
'name' => implode(' ', $name),
'type' => 'directory',
'path' => utf8_substr($image, utf8_strlen(FCPATH . 'image/')),
'href' => site_url('admin/common/filemanager' . '?&token=' . $this->session->userdata('token') . '?&directory=' . utf8_substr($image, utf8_strlen(FCPATH . 'image/' . 'catalog/')) . $url)
);
} elseif (is_file($image)) {
$data['images'][] = array(
'thumb' => $this->model_tool_image->resize(utf8_substr($image, utf8_strlen(FCPATH . 'image/')), 100, 100),
'name' => implode(' ', $name),
'type' => 'image',
'path' => utf8_substr($image, utf8_strlen(FCPATH . 'image/')),
'href' => base_url() . 'image/' . utf8_substr($image, utf8_strlen(FCPATH . 'image/'))
);
}
}
$data['heading_title'] = "Image Manager";
$data['text_no_results'] = "No Results";
$data['text_confirm'] = "Are You Sure";
$data['entry_search'] = "Search..";
$data['entry_folder'] = "New Folder";
$data['button_parent'] = "Parent";
$data['button_refresh'] = "Refresh";
$data['button_upload'] = "Upload";
$data['button_folder'] = "New Folder";
$data['button_delete'] = "Delete";
$data['button_search'] = "Search";
// Session token for ajax
$data['token'] = $this->session->userdata('token');
if (isset($input_get_directory)) {
$data['directory'] = $input_get_directory;
} else {
$data['directory'] = '';
}
// Return the filter name
if (isset($input_get_filter)) {
$data['filter_name'] = $input_get_filter;
} else {
$data['filter_name'] = '';
}
// Return the target ID for the file manager to set the value
if (isset($input_get_target)) {
$data['target'] = $input_get_target;
} else {
$data['target'] = '';
}
// Return the thumbnail for the file manager to show a thumbnail
if (isset($input_get_thumb)) {
$data['thumb'] = $input_get_thumb;
} else {
$data['thumb'] = '';
}
// Parent
$url = '';
if (isset($input_get_directory)) {
$pos = strrpos($input_get_directory, '/');
if ($pos) {
$url .= '?&directory=' . substr($input_get_directory, 0, $pos);
}
}
$data['parent'] = site_url('admin/common/filemanager' .'?&token='. $this->session->userdata('token') . $url);
// Refresh
$url = '';
if (isset($input_get_directory)) {
$url .= '?&directory=' . $input_get_directory;
}
$data['refresh'] = site_url('admin/common/filemanager' .'?&token='. $this->session->userdata('token') . $url);
$this->load->view('template/common/filemanager_view', $data);
}
}

Magento Issues with category dropdown

I need to display all the subcategories under root category name using . I am unable to find the root category details. Root category name is displaying as '/' How to overcome this issue?
Currently i am getting all the categories including root categories (/).
My code is as in below:
public function toOptionArray()
{
$categories = array();
$categoryCollection = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter(
'path',
array('neq' => '1')
);
foreach ($categoryCollection as $category) {
var_dump($category->getData());
echo '<br />';
$category = Mage::getModel('catalog/category')->load($category->getId());
$categories[$category->getId()] = $category->getUrlPath();
}
return $categories;
}
protected function _renderOptions(Varien_Object $row)
{
$categories = $this->getColumn()->getOptions();
$html = sprintf('<select class="category_select" name="mapping[%s]">', $row->getData('reference_id'));
$html .= '<option value=""></option>';
foreach ($categories as $id => $name) {
$html .= sprintf(
'<option value="%s"%s>%s</option>',
$this->escapeHtml($id),
$id == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
}
$html .= '</select>';
return $html;
}
I need to add into the category dropdown, which is subcategories displaying under root category name.
Can anyone help me please.
Thank You.
I fixed the issue using following:
protected function _renderOptions(Varien_Object $row)
{
$categories = $this->getColumn()->getOptions();
$parentIdArray = array();
foreach ($categories as $id => $name) {
$category = Mage::getModel('catalog/category')->load($id);
$parentId = $category->getParentId();
if($parentId == 1){
$parentIdArray[] = $id;
}
}
$html = sprintf('<select class="category_select" name="mapping[%s]">', $row->getData('reference_id'));
$html .= '<option value=""></option>';
foreach ($parentIdArray as $parentId) {
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$name = $parentCategory->getName();
$html .= sprintf(
'<optgroup label="'.$name.'">
<option value="%s"%s>%s</option>
</optgroup>',
$this->escapeHtml($parentId),
$parentId == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
$categories = Mage::getModel('catalog/category')->getCategories($parentId);
$subCategories = $this->get_categories($categories);
foreach ($subCategories as $id => $name) {
$html .= sprintf(
'<option style="padding-left: 10px;" value="%s"%s>%s</option>',
$this->escapeHtml($id),
$id == $row->getData('category_id') ? ' selected="selected"' : '',
$this->escapeHtml($name)
);
}
}
$html .= '</select>';
return $html;
}
public function get_categories($categories) {
$subCategories = array();
foreach($categories as $category) {
$subCategory = Mage::getModel('catalog/category')->load($category->getId());
$subCategories[$subCategory->getId()] = $subCategory->getUrlPath();
if($category->hasChildren()) {
$children = Mage::getModel('catalog/category')->getCategories($category->getId());
$childrenCategories = $this->get_categories($children);
foreach ($childrenCategories as $id => $name) {
$subCategories[$id] = $name;
}
}
}
return $subCategories;
}

Resources