Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

функция добавления товара в корзину


Recommended Posts

вывожу товары определенных категорий на главной (мобильные, пк, ноутбуки и т.д.)

потребовалось добавить одну из опций к мини карточкам товаров на главной - все ок, но только тогда когда добавляю больше одного модуля с товарами (и они повторяются в одном и втором блоке) - проблема с добавлением. пишет что добавлено в корзину но по факту нет. как только убираю второй блок с товарами (например оставляю блок телефоны) - все ок.

 

добавил отдельную функцию добавления в корзину add2, в которой прописываю даже id модуля (для уникальности, чтобы добавлялся товар из конкретного модуля). Потому что если этого не делать, выбрать товар из модуля Смартфоны, а он есть и модуле Телефоны, тогда возникает конфликт. В общем хочу чтобы добавляло товар из конкретного блока (модуля). Видимо нужно просто поправить функцию в js, но никак не вкурю что не так сделал...

 

твиг:

Прихований текст
<div class="sget_box mini_card_box">
  <h3>{{ heading_title }}</h3>
  <div class="swiper-viewport" id="sget{{ sid }}">
    <div id="carousel_sget{{ sid }}" class="swiper-container">
      <div class="swiper-wrapper">
        {% for product in products %}
          <div class="swiper-slide relative">
            <div class="top10">{{ top10 }}</div>
            <div class="mini_add{{ product.product_id }}sget{{ sid }} product-thumb">
              <div class="image"><a href="{{ product.href }}"><img src="{{ product.thumb }}" alt="{{ product.name }}" class="ani"></a></div>
              <div class="caption">
                <h4><a href="{{ product.href }}">{{ product.name }}</a></h4>
                {% if product.price %}
                <div class="price">
                  {% if not product.special %}
                  <span class="price-new">{{ product.price }}</span>
                  {% else %}
                  <span class="price-new">{{ product.special }}</span> <span class="price-old">{{ product.price }}</span>
                  {% endif %}
                </div>
                {% endif %}
                {% if product.pre1 %}
                <ul class="list-unstyled new_list mpre_box">
                  <li>{{ product.pre1 }}</li>
                  {% if product.pre2 %}<li>{{ product.pre2 }}</li>{% endif %}
                  {% if product.pre3 %}<li>{{ product.pre3 }}</li>{% endif %}
                  {% if product.pre4 %}<li>{{ product.pre4 }}</li>{% endif %}
                </ul>
                {% endif %}
              </div>

              {% if product.options %}
              {% for option in product.options %}
                {% if option.option_id == 13 %}
                  {% if option.type == 'select' %}
                  <div class="form-group{% if option.required %} required{% endif %} cat_option">
                    <select name="option[{{ option.product_option_id }}]" id="input-option{{ option.product_option_id }}" class="form-control ani">
                      {% for option_value in option.product_option_value %}
                      <option value="{{ option_value.product_option_value_id }}">{{ option_value.name }}
                      {% if option_value.price %}
                      ({{ option_value.price_prefix }}{{ option_value.price }})
                      {% endif %} </option>
                      {% endfor %}
                    </select>
                  </div>
                  {% endif %}
                {% endif %}
              {% endfor %}
              {% endif %}

              <div class="button-group but_box">
                <input type="hidden" name="product_id" value="{{ product.product_id }}">
                <input type="hidden" name="quantity" value="{{ product.minimum }}">
                <button type="button" class="add_cart" onclick="cart.add2('{{ product.product_id }}', 'sget{{ sid }}');">{{ button_cart }}</button>
                <span class="dop_but">
                  <button type="button" data-toggle="tooltip" title="{{ button_compare }}" onclick="compare.add('{{ product.product_id }}');"><img src="/image/catalog/icons/compare.png"></button>
                  <button type="button" data-toggle="tooltip" title="{{ button_wishlist }}" onclick="wishlist.add('{{ product.product_id }}');"><img src="/image/catalog/icons/like.png"></button>
                </span>
              </div>
            </div>
          </div>
        {% endfor %}
      </div>
    </div>
    <div class="swiper-pagination carousel_sget{{ sid }}"></div>
    <div class="swiper-pager hidden">
      <div class="swiper-button-next"></div>
      <div class="swiper-button-prev"></div>
    </div>
  </div>
  <script type="text/javascript">
    $('#carousel_sget{{ sid }}').swiper({
      mode: 'horizontal',
      slidesPerView: 4,
      pagination: '.carousel_sget{{ sid }}',
      paginationClickable: true,
      nextButton: '.swiper-button-next',
      prevButton: '.swiper-button-prev',
      autoplay: 10000,
      speed: 2500,
      spaceBetween: 75,
      pauseOnMouseEnter: true,
      dynamicBullets: true,
      loop: false
    });
  </script>
</div>

 

 

 

контроллер:

Прихований текст
<?php
class ControllerExtensionModuleBycategory extends Controller {
public function index($setting) {
	$this->load->model('catalog/product');
	$this->load->model('catalog/category');
	$this->load->model('tool/image');
	
		$data['products'] = array();

		$data['category_info'] = $this->model_catalog_category->getCategory($setting['category_id']);
		if($data['category_info']){
			$data['heading_title'] = $data['category_info']['name'];
		}else{
			$data['heading_title'] = '';
		}

		$data['sid'] = $setting['category_id'];
		
		if($data['category_info']){
			$data['catimag'] = $this->model_tool_image->resize($data['category_info']['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_popup_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_popup_height'));
		}else{
			$data['catimag'] = $this->model_tool_image->resize('placeholder.png', $this->config->get('theme_' . $this->config->get('config_theme') . '_image_popup_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_popup_height'));
		}


		$data['category_link'] = $this->url->link('product/category', 'path=' . $setting['category_id'],'SSL');

		$results = $this->model_catalog_product->getProductsByCategory($setting['category_id'],$setting['limit']);
		//echo $setting['category_id'];
		foreach ($results as $result) {
			if ($result['image']) {
				$image = $this->model_tool_image->resize($result['image'], $setting['width'], $setting['height']);
			} else {
				$image = false;
			}


			if ((float)$result['price']) {
				$mrp_percentage = round(100 - (($result['price']*100) / $result['price']));
			} else {
				$mrp_percentage = false;
			}
			
			if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
				$price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')),$this->session->data['currency']);
			} else {
				$price = false;
			}
					
			if ((float)$result['special']) {
				$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')),$this->session->data['currency']);
			} else {
				$special = false;
			}
			
			if ($this->config->get('config_review_status')) {
				$rating = $result['rating'];
			} else {
				$rating = false;
			}
			
			if ((float)$result['special']) {
				$special_percentage = round(100 - (($result['special']*100) / $result['price']));
			} else {
				$special_percentage = false;
			}

			$options = array();

			foreach ($this->model_catalog_product->getProductOptions($result['product_id']) as $option) {
				$product_option_value_data = array();

				foreach ($option['product_option_value'] as $option_value) {
					if (!$option_value['subtract'] || ($option_value['quantity'] > 0)) {
						if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
							$opt_price = $this->currency->format($this->tax->calculate($option_value['price'], $result['tax_class_id'], $this->config->get('config_tax') ? 'P' : false), $this->session->data['currency']);
						} else {
							$opt_price = false;
						}

						$product_option_value_data[] = array(
							'product_option_value_id' => $option_value['product_option_value_id'],
							'option_value_id'         => $option_value['option_value_id'],
							'name'                    => $option_value['name'],
							'image'                   => $this->model_tool_image->resize($option_value['image'], 50, 50),
							'price'                   => $opt_price,
							'price_prefix'            => $option_value['price_prefix']
						);
					}
				}

				$options[] = array(
					'product_option_id'    => $option['product_option_id'],
					'product_option_value' => $product_option_value_data,
					'option_id'            => $option['option_id'],
					'name'                 => $option['name'],
					'type'                 => $option['type'],
					'value'                => $option['value'],
					'required'             => $option['required']
				);
			}
		
			$data['products'][] = array(
				'name' 			=> utf8_substr(strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')), 0, 50),
				'product_id' 	=> $result['product_id'],
				'model' 		=> $result['model'],
				'description' 	=> html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8'),
				'thumb'   	 	=> $image,
				'price'   	 	=> $price,
				'rating'     	=> $rating,
				'special' 	 	=> $special,
				'special_percentage' =>$special_percentage,
				'pre1'          => $result['sku'],
				'pre2'          => $result['upc'],
				'pre3'          => $result['ean'],
				'pre4'          => $result['jan'],
				'options'       => $options,
				'href'     	 	=> $this->url->link('product/product', 'product_id=' . $result['product_id'],'SSL')
			);
		}
			return $this->load->view('extension/module/bycategory', $data);
	}
    
function friendlyURL($string){
	$string = preg_replace("`\[.*\]`U","",$string);
	$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string);
	$string = htmlentities($string, ENT_COMPAT, 'utf-8');
	$string = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $string );
	$string = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $string);
	return strtolower(trim($string, '-'));
}
}
?>

 

 

 

новая функция в common.js

Прихований текст
'add2': function(product_id, prefix) {
		$.ajax({
			url: 'index.php?route=checkout/cart/add',
			type: 'post',
			data: $('.mini_add'+product_id+''+prefix+' input[type=\'text\'], .mini_add'+product_id+''+prefix+' input[type=\'hidden\'], .mini_add'+product_id+''+prefix+' input[type=\'radio\']:checked, .mini_add'+product_id+''+prefix+' input[type=\'checkbox\']:checked, .mini_add'+product_id+''+prefix+' select, .mini_add'+product_id+''+prefix+' textarea'),
			dataType: 'json',
			beforeSend: function() {
				$('#cart > button').button('loading');
			},
			complete: function() {
				$('#cart > button').button('reset');
			},
			success: function(json) {
				$('.alert-dismissible, .text-danger').remove();

				if (json['redirect']) {
					location = json['redirect'];
				}

				if (json['success']) {
					$('#content').parent().before('<div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');

					$('.cart_num').html('<div class="flex3">' + json['total'] + '</div>');

					$('html, body').animate({ scrollTop: 0 }, 'slow');

					$('#cart > ul').load('index.php?route=common/cart/info ul li');
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	},

 

 

 

 

 

Link to comment
Share on other sites


В 02.01.2023 в 11:35, chukcha сказав:

Сам метод кривоват

У вас может быть несколько одинаковых продуктов

 

 

на удивление с кодом все ок, вся конструкция в норме. проблема оказалась в том что забыл в контроллер добавить это:

'minimum'     => $result['minimum'],

 

Link to comment
Share on other sites


Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.