Jump to content

Recommended Posts

Добрый день.

 

Есть код создание фильтра по товарам ajax я не совсем понимаю где что правильно создать я о папках не понятно где они должны быть в корне или в самой теме. Можете подсказать что куда запилить. Заранее спасибо

 

У меня версия Simpla 2.3.8

 

Сам код

Код формы фильтра filter.tpl:

<div class="filters">
	<form id="filter" method="get" action="/ajax/products.php">
	<input type="hidden" name="page" value="1">
	<input type="hidden" name="category" value="{$category->children|@json_encode}">
	<div class="filter">
		<h3 class="title thin">Сортировка</h3>
		<div class="radio">
		  <input id="rd-1" type="radio" name="sort" value="position" {if $sort=='position'}checked{/if}>	
		  <label for="rd-1">Позиция (популярные)</label>
		</div>
		<div class="radio">
		  <input id="rd-2" type="radio" name="sort" value="price" {if $sort=='price'}checked{/if}>	
		  <label for="rd-2">Цена (от дешевых)</label>
		</div>
		<div class="radio">
		  <input id="rd-3" type="radio" name="sort" value="name" {if $sort=='name'}checked{/if}>	
		  <label for="rd-3">Название (А-Я)</label>
		</div>
	</div>
	<div class="filter">
		<h3 class="title thin">Стоимость</h3>
		<input name="cost" type="text" id="range" data-min="{$min_price}" data-max="{$max_price}" data-postfix=" {$currency->sign|escape}" data-type="double" value="" />
	</div>
	{if $features}
	{foreach $features as $f}
	<div class="filter">
		<h3 class="title thin">{$f->name}</h3>
		{foreach $f->options as $o key=i}
		<div class="checkbox">
		  <input id="ch-{$f->id}-{$i}" type="checkbox" name="features[{$f->id}][]" value="{$o->value}">	
		  <label for="ch-{$f->id}-{$i}">{$o->value|escape}</label>
		</div>
		{/foreach}
	</div>
	{/foreach}
	{/if}
	</form>
</div>

Модифицыруем запросы к БД:

Правим файл api/Products.php

//все строчки
$features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? ) ', $feature, $value);
//заменяем на
$features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value in ('.$value.') ) ', $feature);

Добавляем контроллер

Добавляем файл ajax/products.php, который будет возвращать список продуктов, соответствующий фильтру.

<?PHP
if(!isset($_SESSION)){session_start();}
require_once('../api/Simpla.php');
$simpla = new Simpla();

// Валюты
$simpla->currencies = $simpla->money->get_currencies(array('enabled'=>1));
if(isset($_SESSION['currency_id']))
	$simpla->currency = $simpla->money->get_currency($_SESSION['currency_id']);
else
	$simpla->currency = reset($simpla->currencies);

$simpla->design->assign('currency',	$simpla->currency);

// GET-Параметры
$request_category = $simpla->request->get('category', 'string');
$request_sort = $simpla->request->get('sort', 'string');
$request_cost = explode(';',$simpla->request->get('cost'));
$request_features = $simpla->request->get('features');


$filter = array();
$filter['visible'] = 1;	


if ($request_category)
{
	$filter['category_id'] = json_decode($request_category, true);
}

// Сортировка товаров, сохраняем в сесси, чтобы текущая сортировка оставалась для всего сайта
if($sort = $request_sort){
	$_SESSION['sort'] = $sort;		
}
if (!empty($_SESSION['sort'])){
	$filter['sort'] = $_SESSION['sort'];			
}
else{
	$filter['sort'] = 'position';			
}


// Свойства товаров
if($request_features){
	$features = array();
	foreach ($request_features as $feature_id => $value) {
		$features[$feature_id] = '"'.implode('","',$value).'"';
	}
	$filter['features'] = $features;
}


// Постраничная навигация
$items_per_page = $simpla->settings->products_num;		
// Текущая страница в постраничном выводе
$current_page = $simpla->request->get('page', 'int');	
// Если не задана, то равна 1
$current_page = max(1, $current_page);
$simpla->design->assign('current_page_num', $current_page);
// Вычисляем количество страниц
$products_count = $simpla->products->count_products($filter);

// Показать все страницы сразу
if($simpla->request->get('page') == 'all')
	$items_per_page = $products_count;	

$pages_num = ceil($products_count/$items_per_page);
$simpla->design->assign('total_pages_num', $pages_num);
$simpla->design->assign('total_products_num', $products_count);

$filter['page'] = $current_page;
$filter['limit'] = $items_per_page;


$discount = 0;
if(isset($_SESSION['user_id']) && $user = $simpla->users->get_user(intval($_SESSION['user_id']))){
	$discount = $user->discount;
}

// Товары 
$products = array();
foreach($simpla->products->get_products($filter) as $p){
	$products[$p->id] = $p;
}

if(!empty($products))
{
	$products_ids = array_keys($products);
	foreach($products as &$product)
	{
		$product->variants = array();
		$product->images = array();
		$product->properties = array();
	}

	$variants = $simpla->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true));
	
	foreach($variants as &$variant)
	{
		//$variant->price *= (100-$discount)/100;
		$products[$variant->product_id]->variants[] = $variant;
	}

	$images = $simpla->products->get_images(array('product_id'=>$products_ids));
	foreach($images as $image)
		$products[$image->product_id]->images[] = $image;

	foreach($products as &$product)
	{
		if(isset($product->variants[0]))
			$product->variant = $product->variants[0];
		if(isset($product->images[0]))
			$product->image = $product->images[0];
	}

	$simpla->design->assign('products', $products);
}


	
$output = $simpla->design->fetch('view/ajax/products.tpl');
echo $output;
return false;

Добавляем шаблон вывода товаров

Создаем файл design/theme/view/ajax/products.tpl

{if $products}
<div class="row">
	{foreach $products as $product}
		{include file="view/product/grid.product.tpl"}
	{/foreach}
</div>
{else}
Товары не найдены
{/if}

{include file='view/base/pagination.tpl'}

Делаем пагинацию pagination.tpl

<div class="pagination">
	<ul class="ul">
	{if $total_pages_num > 1}

		{if $current_page_num != 1}
		<li><a href="{$current_page_num-1}"><i class="fa fa-angle-left"></i></a></li>
		{else}
		<li><span><i class="fa fa-angle-left"></i></span></li>
		{/if}

		{for $page=1 to $total_pages_num}
			<li class="{if $page == $current_page_num}active{/if}"><a href="{$page}">{$page}</a></li>
		{/for}

		{if $current_page_num<$total_pages_num}
		<li><a href="{$current_page_num+1}"><i class="fa fa-angle-right"></i></a></li>
		{else}
		<li><span><i class="fa fa-angle-right"></i></span></li>
		{/if}

	{/if}
	</ul>
</div>

Добавим JavaScript

$('form#filter').on('change','input:not([name=cost])',function(e){
  e.preventDefault();
  $('form#filter input[name=page]').val(1);
  ajaxFilter();
});


$('#products').on('click','.pagination li a',function(e){
  e.preventDefault();
  var page = $(this).attr('href');
  $('form#filter input[name=page]').val(page);
  ajaxFilter();
});

//price slider
$('#range').ionRangeSlider({
  grid: true,
  onFinish: function (data) {
    $('form#filter input[name=page]').val(1);
    ajaxFilter();
  }
});

var ajaxFilter = function(){
  $.ajax({
    url: $('form#filter').attr('action'),
    data: $('form#filter').serialize()
  }).done(function(response){
    $('#products').html(response);
    fixHeights();
    $('html, body').animate({
      scrollTop: $("#products").offset().top-30
    }, 500);
  });
};

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...