Перейти к публикации
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

Вывод главной категории товара на страницу Спасипотому что (success).


 Погделиться

Рекомендованные сообещёния

Как вывести Главную категорию товара на страницу Спасипотому что (success)?

Вот контроллер:

Спойлер
<?php
class ControllerCheckoutSuccess extends Controller {
	public function index() {
	    
	    
	    
$data['order'] = array();
$data['products'] = array();
	    
if (isset($this->session->data['order_id'])) {
    $order_id = $this->session->data['order_id'];
    $this->load->model('account/order');
    $order_info = $this->model_account_order->getOrder($order_id);
    if ($order_info) {
        $tax = 0;
        $shipping = 0;
        $order_totals = $this->model_account_order->getOrderTotals($order_id);
        foreach ($order_totals as $order_total) {
            if ($order_total['code'] == 'tax') {
                $tax += $order_total['value'];
            } elseif ($order_total['code'] == 'shipping') {
                $shipping += $order_total['value'];
            }
        }
              
//запрос данных о заказе
        $data['order'] = $order_info;
        $data['order']['store_name'] = $this->config->get('config_name');
        $data['order']['order_total'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value'], false);
        $data['order']['order_tax'] = $this->currency->format($tax, $order_info['currency_code'], $order_info['currency_value'], false);
        $data['order']['order_shipping'] = $this->currency->format($shipping, $order_info['currency_code'], $order_info['currency_value'], false);
              
// запрос данных о товарах в заказе
        $products = $this->model_account_order->getOrderProducts($order_id);
        $this->load->model('catalog/product');
        $this->load->model('catalog/category');
        foreach ($products as $product) {
            $sku = '';
            $product_info = $this->model_catalog_product->getProduct($product['product_id']);
            if ($product_info) {
                $sku = $product_info['sku'];
            }
            $categories = array();
            $product_categories = $this->model_catalog_product->getCategories($product['product_id']);
            if ($product_categories) {
                foreach ($product_categories as $product_category) {
                    $category_data = $this->model_catalog_category->getCategory($product_category['category_id']);
                    if ($category_data) {
                        $categories[] = $category_data['name'];
                    }
                }
            }
              
$data['products'][] = array(
                'order_id' => $order_id,
                'product_id' => $product['product_id'],
                'sku' => $sku,
                'name' => $product['name'],
                'category' => implode(',', $categories),
                'quantity' => $product['quantity'],
                'price' => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value'], false)
            );
        }
    }
}
	    
		$this->load->language('checkout/success');
		if (isset($this->session->data['order_id'])) {
		    
			$this->cart->clear();
			// Add to activity log
			if ($this->config->get('config_customer_activity')) {
				$this->load->model('account/activity');
				if ($this->customer->isLogged()) {
					$activity_data = array(
						'customer_id' => $this->customer->getId(),
						'name'        => $this->customer->getFirstName() . ' ' . $this->customer->getLastName(),
						'order_id'    => $this->session->data['order_id']
					);
					$this->model_account_activity->addActivity('order_account', $activity_data);
				} else {
					$activity_data = array(
						'name'     => $this->session->data['guest']['firstname'] . ' ' . $this->session->data['guest']['lastname'],
						'order_id' => $this->session->data['order_id']
					);
					$this->model_account_activity->addActivity('order_guest', $activity_data);
				}
			}
			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['guest']);
			unset($this->session->data['comment']);
			unset($this->session->data['order_id']);
			unset($this->session->data['coupon']);
			unset($this->session->data['reward']);
			unset($this->session->data['voucher']);
			unset($this->session->data['vouchers']);
			unset($this->session->data['totals']);
		}
		$this->document->setTitle($this->language->get('heading_title'));
		$data['breadcrumbs'] = array();
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home')
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_basket'),
			'href' => $this->url->link('checkout/cart')
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_checkout'),
			'href' => $this->url->link('checkout/checkout', '', true)
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_success'),
			'href' => $this->url->link('checkout/success')
		);
		$data['heading_title'] = $this->language->get('heading_title');
		if ($this->customer->isLogged()) {
			$data['text_message'] = sprintf($this->language->get('text_customer'), $this->url->link('account/account', '', true), $this->url->link('account/order', '', true), $this->url->link('account/download', '', true), $this->url->link('information/contact'));
		} else {
			$data['text_message'] = sprintf($this->language->get('text_guest'), $this->url->link('information/contact'));
		}
		$data['button_continue'] = $this->language->get('button_continue');
		$data['continue'] = $this->url->link('common/home');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['column_right'] = $this->load->controller('common/column_right');
		$data['content_top'] = $this->load->controller('common/content_top');
		$data['content_bottom'] = $this->load->controller('common/content_bottom');
		$data['footer'] = $this->load->controller('common/footer');
		$data['header'] = $this->load->controller('common/header');
		$this->response->setOutput($this->load->view('common/success', $data));
	}
}

 

В шаблоне пыиюсь выводить вот ик:

<?php echo $product['category']; ?>

Выводит все категории, в которых есть этот товар.

Как вывести только Главную?

Ссылка на комменирий
Погделиться на других сайих


Вот тут нужно поменять:

if ($product_categories) {
  foreach ($product_categories as $product_category) {
    $category_data = $this->model_catalog_category->getCategory($product_category['category_id']);
    if ($category_data) {
	    $categories[] = $category_data['name'];
    }
  }
}

нужно ик сгделать:

if ($product_categories) {
  foreach ($product_categories as $product_category) {
    if ((int)$product_category['main_category']) {
      $category_data = $this->model_catalog_category->getCategory($product_category['category_id']);
      if ($category_data) {
          $categories[] = $category_data['name'];
      }
    }
  }
}

 

  • +1 1
Ссылка на комменирий
Погделиться на других сайих

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

  • +1 1
Ссылка на комменирий
Погделиться на других сайих

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

Вот тут нужно поменять:

В шаблон ик?

<?php echo $product_category['main_category']; ?>

Если да, то:

Notice: Undefined variable: product_category in line 28

Ссылка на комменирий
Погделиться на других сайих


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

почему в шаблон?
Вы же дали код контроллера

Разобрался. Спасипотому что потому чтольшое!

Ссылка на комменирий
Погделиться на других сайих


Создайте аккаунт или войдите в него для комментирования

Вы должны быть пользователем, чтобы осивить комменирий

Создать аккаунт

Зарегистрируйтесь для получения аккауни. Это просто!

Зарегистрировать аккаунт

Войти

Уже зарегистрированы? Войдите згдесь.

Войти сейчас
 Погделиться

×
×
  • Создать...

Важная информация

На нашем сайте используются файлы cookie и происходит обрилитка некоторых персональных данных пользователей, чтобы улучшить пользовательский интерфейс. Чтобы узнать для чего и какие персональные данные мы обрабатываем перейдите по ссылке. Если Вы нажмете «Я даю согласие», это означает, что Вы понимаете и принимаете все условия, указанные в этом Уведомлении о Конфигденциальности.