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

Вывод главной категории ocstore 3


Recommended Posts

Помогите, пожалуйси, вывести наименование главной категории в модуль (аналог рекомендуемых/хитов/новинок). Суть в следуюещём: на главной выводится четыре модуля с товарами. Каждый модуль - отгдельная категория товаров. То есть, четыре категории товаров = четыре модуля. В каждом из модулей выводятся заголовок (категория, которая прикреплена к товару второй, указывается в админке) и товары из соответствуюещёй категории в вигде карточек (картинка, название, главная категория, которую пыиюсь вывести и этона).

До этого на другом сайте гделал вывод основной категории в карточке товара (в могдели получал id категории из базы данных, затем получал имя в контроллере и в шаблоне уже выводил), а згдесь никак не могу сообразить (в php и sql я нулевой, только учусь:-)). Да же пропотому чтовал получать id главной категории в могдели продуки, а в контроллере модуля ее получать, но при вывогде липотому что ничего, липотому что "0".

 

Спойлер

Могдель продуки:   

 public function getProductMainCategoryId($product_id) {
        $query = $this->db->query("SELECT category_id FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int)$product_id . "' AND main_category = '1' LIMIT 1");
        return ($query->num_rows ? (int)$query->row['category_id'] : 0);
    }
    
    public function getProductMainCategoryName($main_category_id) {
        $query = $this->db->query("SELECT name FROM " . DB_PREFIX . "category_description WHERE category_id = '" . (int)$main_category_id. "'");
        return ($query->num_rows ? $query->row['name'] : 0);
    }    

Спойлер

Контроллер модуля:

<?php
class ControllerExtensionModuleTproproduct extends Controller {
    public function index($setting) {
        $this->load->language('extension/module/tproproduct');

        $data['lang'] = $this->language->get('code');
        
        $data['heading_title'] = $this->language->get('heading_title');
        $data['text_tax'] = $this->language->get('text_tax');
        $data['button_cart'] = $this->language->get('button_cart');
        $data['button_wishlist'] = $this->language->get('button_wishlist');
        $data['button_compare'] = $this->language->get('button_compare');

        $this->load->model('catalog/category');
        
        $this->load->model('catalog/manufacturer');
        
        if (isset($this->request->get['product_id'])) {
            $product_id = (int)$this->request->get['product_id'];
        } else {
            $product_id = 0;
        }        

        $this->load->model('catalog/product');
        
        $product_info = $this->model_catalog_product->getProduct($product_id);
        
        if ($product_info) {
            
            $this->document->addLink($this->url->link('product/product', 'product_id=' . $this->request->get['product_id']), 'canonical');
            
            $this->load->model('catalog/review');
            
            $data['product_id'] = (int)$this->request->get['product_id'];
            
            $main_category_id = $this->model_catalog_product->getProductMainCategoryId((int)$this->request->get['product_id']); //вывод категорий
            
            $data['category_name'] = $this->model_catalog_product->getProductMainCategoryName($main_category_id);
            
        }
        

        $this->load->model('tool/image');

        $data['categories'] = array();

        if (!$setting['limit']) {
            $setting['limit'] = 4;
        }

        if (!empty($setting['category'])) {
            $categories = array_slice($setting['category'], 0, (int)$setting['limit']);

            foreach ($categories as $category_id) {
                $category_info = $this->model_catalog_category->getCategory($category_id);

                if ($category_info) {
                    
                    $products = array();

                    $filter_data = array(
                        'filter_category_id' => $category_id,
                        'filter_sub_category' => true,
                        'start'              => 0,
                        'limit'              => $setting['limit']
                    );

                    $product_total = $this->model_catalog_product->getTotalProducts($filter_data);

                    $results = $this->model_catalog_product->getProducts($filter_data);

                    if ($category_info['image']) {
                        $data['thumb'] = $this->model_tool_image->resize($category_info['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_category_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_category_height'));
                    } else {
                        $data['thumb'] = '';
                    }                    
                    
                    foreach ($results as $result) {
                        if($result){
                        if ($result['image']) {
                            $image = $this->model_tool_image->resize($result['image'], $setting['width'], $setting['height']);
                        } else {
                            $image = $this->model_tool_image->resize('placeholder.png', $setting['width'], $setting['height']);
                        }

                        if ($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_tax')) {
                            $tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price'], $this->session->data['currency']);
                        } else {
                            $tax = false;
                        }

                        if ($this->config->get('config_review_status')) {
                            $rating = (int)$result['rating'];
                        } else {
                            $rating = false;
                        }

                        $products[] = array(
                            'product_id'  => $result['product_id'],
                            'thumb'       => $image,
                            'name'        => $result['name'],
                            'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get('theme_' . $this->config->get('config_theme') . '_product_description_length')) . '..',
                            'price'       => $price,
                            'special'     => $special,
                            'tax'         => $tax,
                            'rating'      => $rating,
                            'href'        => $this->url->link('product/product', 'product_id=' . $result['product_id'])
                            );
                        }
                     }
                    $data['categories'][] = array(
                        'category_id' => $category_info['category_id'],
                        'products'      => $products,
                        'name'        => $category_info['name'],
                        'href'        => $this->url->link('product/category', 'path=' . $category_info['category_id'])
                    );
                }
            }
        }
        if ($data['categories']) {
                return $this->load->view('extension/module/tproproduct', $data);
        }
    }
}

Спойлер

Шаблон:

<p class="card-text">{{ category_name }}</p>

 

  • +1 1
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.