Jump to content
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

Плюс/Минус


mss
 Share

Recommended Posts

Здравствуйте!

Подскажите пжл, как реализовать в категории Плюс/минус вместо кнопки "Купить".

http://joxi.ru/52a1l8GiEJEpy2

 

По нажатию Плюс - товар добавляется в корзину(+1)

По нажатию Минус - Минусуется с корзины(-1)

Link to comment
Share on other sites


17 минут назад, mss сказал:

По нажатию Плюс - товар добавляется в корзину(+1)

По нажатию Минус - Минусуется с корзины(-1)

С плюсом всё легко - просто вызываете событие add которое на кнопке купить, оно и бугдет добавлять. А вот с уднонием сложнее. Смотрите как это сгделано в корзине. В корзине удноние игдет по cart_id товара в корзине. Вам нужно найти все товары которые сейчас в корзине покупателя, выбрать только тот у которого product_id равен тому на котором тыкнули минус и уменьшить его когдачество. Недавно обсуждал подобную тему, может натолкнёт вас на нужные мысли

 

Link to comment
Share on other sites

10 минут назад, iglin сказал:

С плюсом всё легко - просто вызываете событие add которое на кнопке купить, оно и бугдет добавлять.

Ага, с плюсом - проблем нет.

 

11 минут назад, iglin сказал:

с уднонием сложнее

с минусом - пока не понятно

Link to comment
Share on other sites


Только что, mss сказал:

с минусом - пока не понятно

Ну если прям совсем образно, то нужно в js создать функцию del например по аналогии с add, в ней обращаться через ajax на новую функцию которую вы создадите в контроллере checkout/cart (пример икой функции я выше дал, но им полное удноние товара, в вашем случае нужно перегделать и менять когдачество на -1, ну или удалять если всего 1 в корзине), дальше через js перерисовывать ик же корзину как при добавлении... 

 

  • +1 1
Link to comment
Share on other sites

common.js

$(function(){
	$('.btn-remove-in-cart').click(function(){
		let product_id = $(this).attr('data-productid');

		$.ajax({
			url: 'index.php?route=checkout/cart/removeAllProductsForCartId',
			type:'post',
			dataType:'json',
			data:{'product_id': product_id},
			success: function(res){
				// тут, обновляем корзину
				// удаляем кнопку
			}
		})
	})
});

model/product

public function getProductsCartId($product_id){
        $query = $this->db->query("SELECT cart_id  FROM " . DB_PREFIX . "cart  WHERE product_id = '" . (int) $product_id . "' AND api_id = '" . (isset($this->session->data['api_id']) ? (int) $this->session->data['api_id'] : 0) . "' AND customer_id = '" . (int) $this->customer->getId() . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");

        return $query->rows;
    }

category.php

$query_cart_id = $this->model_catalog_product->getProductsCartId($result['product_id']);
                $in_cart = false;
                if($query_cart_id){
                    $in_cart = true;
                }


...
'in_cart' => $in_cart,

category.tpl

<?php if($product['in_cart']){?>
              <button data-productid="<?php echo $product['product_id']; ?>" class="btn-remove-in-cart btn btn-default">Удалить из корины</button>
              <?php } ?>

 

Link to comment
Share on other sites


2 минуты назад, mss сказал:

common.js

$(function(){
	$('.btn-remove-in-cart').click(function(){
		let product_id = $(this).attr('data-productid');

		$.ajax({
			url: 'index.php?route=checkout/cart/removeAllProductsForCartId',
			type:'post',
			dataType:'json',
			data:{'product_id': product_id},
			success: function(res){
				// тут, обновляем корзину
				// удаляем кнопку
			}
		})
	})
});

model/product

public function getProductsCartId($product_id){
        $query = $this->db->query("SELECT cart_id  FROM " . DB_PREFIX . "cart  WHERE product_id = '" . (int) $product_id . "' AND api_id = '" . (isset($this->session->data['api_id']) ? (int) $this->session->data['api_id'] : 0) . "' AND customer_id = '" . (int) $this->customer->getId() . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");

        return $query->rows;
    }

category.php

$query_cart_id = $this->model_catalog_product->getProductsCartId($result['product_id']);
                $in_cart = false;
                if($query_cart_id){
                    $in_cart = true;
                }


...
'in_cart' => $in_cart,

category.tpl

<?php if($product['in_cart']){?>
              <button data-productid="<?php echo $product['product_id']; ?>" class="btn-remove-in-cart btn btn-default">Удалить из корины</button>
              <?php } ?>

 

контроллер cart

public function removeAllProductsForCartId(){
        $this->load->language('checkout/cart');

        $json = array();

        // Remove
        if (isset($this->request->post['key'])) {
            $products = $this->cart->getProducts();
            foreach ($products as $product) {
                if ($product['product_id'] == $this->request->post['key']) {
                    $this->cart->remove($product['cart_id']);

                    unset($this->session->data['vouchers'][$product['cart_id']]);
                }
            }

            $json['success'] = $this->language->get('text_remove');

            unset($this->session->data['shipping_method']);
            unset($this->session->data['shipping_methods']);
            unset($this->session->data['payment_method']);
            unset($this->session->data['payment_methods']);
            unset($this->session->data['reward']);

            // Totals
            $this->load->model('extension/extension');

            $totals = array();
            $taxes = $this->cart->getTaxes();
            $total = 0;

            // Because __call can not keep var references so we put them into an array.
            $total_data = array(
                'totals' => &$totals,
                'taxes'  => &$taxes,
                'total'  => &$total
            );

            // Display prices
            if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $sort_order = array();

                $results = $this->model_extension_extension->getExtensions('total');

                foreach ($results as $key => $value) {
                    $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
                }

                array_multisort($sort_order, SORT_ASC, $results);

                foreach ($results as $result) {
                    if ($this->config->get($result['code'] . '_status')) {
                        $this->load->model('extension/total/' . $result['code']);

                        // We have to put the totals in an array so that they pass by reference.
                        $this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
                    }
                }

                $sort_order = array();

                foreach ($totals as $key => $value) {
                    $sort_order[$key] = $value['sort_order'];
                }

                array_multisort($sort_order, SORT_ASC, $totals);
            }

            $json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total, $this->session->data['currency']));
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

 

Link to comment
Share on other sites


9 минут назад, mss сказал:

кнопка Удалить из корзины появилась, но не удаляет

ну как минимум в js у вас data:{'product_id': product_id}, а в removeAllProductsForCartId вы ждёте key

Link to comment
Share on other sites

34 минуты назад, iglin сказал:

ну как минимум в js у вас data:{'product_id': product_id}, а в removeAllProductsForCartId вы ждёте key

копипаст, он икой.  

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.