Simpla 2.1+: дополнительные чекбоксы в товаре

Скачать Simpla 2.1+: дополнительные чекбоксы в товаре
Сейчас ищут:

Bogusua

Житель
Регистрация
28.05.15
Сообщения
96
Реакции
115
в продолжение поста с запросом о помощи с симплой http://itnull.ru/threads/pomogu-s-simploj.2248/page-2#post-18026


1 - В рабочую базу магазина исполняем запрос
Код:
ALTER TABLE `s_products` ADD `is_new` TINYINT( 1 ) NOT NULL AFTER `visible`
2 - открываем файла админки simpla/design/html/product.tpl и ищем код
Код:
        <div class="checkbox">
            <input name=featured value="1" type="checkbox" id="featured_checkbox" {if $product->featured}checked{/if}/> <label for="featured_checkbox">Рекомендуемый</label>
        </div>
После него вставляем
Код:
<div class="checkbox">
    <input name="is_new" value="1" type="checkbox" id="new_checkbox" {if $product->is_new}checked{/if} /> <label for="new_checkbox">Новинка  {if $product->is_new}checked{else} not cheked {/if}</label>
</div>
3 - открываем фай simpla/productAdmin.php и находим строку
Код:
$product->featured = $this->request->post('featured');
и после нее добавляем
Код:
$product->is_new = $this->request->post('is_new', 'boolean');
4 - Открываем файл api/Products.php и находим строку
Код:
$features_filter = '';
и после нее добавляем
Код:
$is_new_filter = '';
5 - Далее в этом же файле ищем
Код:
if(isset($filter['featured']))
    $is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured']));
и добавляем
Код:
if(isset($filter['is_new']))
    $is_new_filter = $this->db->placehold('AND p.is_new=?', intval($filter['is_new']));
6 - Далее находим тут же SQL запрос вида
Код:
$query = "SELECT
            p.id,
            p.url,
            p.brand_id,
            p.name,
            p.annotation,
            p.body,
            p.position,
            p.created as created,
            p.visible,
            p.featured,
            p.meta_title,
            p.meta_keywords,
            p.meta_description,
            b.name as brand,
            b.url as brand_url
        FROM s_products p 
        $category_id_filter
        LEFT JOIN s_brands b ON p.brand_id = b.id
        WHERE
            1
            $product_id_filter
            $brand_id_filter
            $features_filter
            $keyword_filter
            $is_featured_filter
            $discounted_filter
            $in_stock_filter
            $visible_filter
        $group_by
        ORDER BY $order
            $sql_limit";
и обновляем его с учетом нашего нового фильтра
Код:
$query = "SELECT
            p.id,
            p.url,
            p.brand_id,
            p.name,
            p.annotation,
            p.body,
            p.position,
            p.created as created,
            p.visible,
p.is_new,
            p.featured,
            p.meta_title,
            p.meta_keywords,
            p.meta_description,
            b.name as brand,
            b.url as brand_url
        FROM s_products p 
        $category_id_filter
        LEFT JOIN s_brands b ON p.brand_id = b.id
        WHERE
            1
            $product_id_filter
            $brand_id_filter
            $features_filter
            $keyword_filter
$is_new_filter
            $is_featured_filter
            $discounted_filter
            $in_stock_filter
            $visible_filter
        $group_by
        ORDER BY $order
            $sql_limit";
7 - продолжаем тут же, ищем строку
Код:
public function count_products($filter = array())
под ней будет идти перечень переменных
Код:
        $category_id_filter = '';
        $brand_id_filter = '';
        $product_id_filter = '';
        $keyword_filter = '';
        $visible_filter = '';
        $is_featured_filter = '';
        $in_stock_filter = '';
        $discounted_filter = '';
        $features_filter = '';
и обновляем его с учетом нашего нового фильтра
Код:
        $category_id_filter = '';
        $brand_id_filter = '';
        $product_id_filter = '';
        $keyword_filter = '';
        $visible_filter = '';
$is_new_filter = '';
        $is_featured_filter = '';
        $in_stock_filter = '';
        $discounted_filter = '';
        $features_filter = '';
8 - далее ищем код
Код:
        if(isset($filter['featured']))
            $is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured']));
после него добавляем
Код:
if(isset($filter['is_new']))
            $is_new_filter = $this->db->placehold('AND p.is_new=?', intval($filter['is_new']));
9 - ищем SQL запрос чуть ниже, он такого вида
Код:
        $query = "SELECT count(distinct p.id) as count
                FROM __products AS p
                $category_id_filter
                WHERE 1
                    $brand_id_filter
                    $product_id_filter
                    $keyword_filter
                    $is_featured_filter
                    $in_stock_filter
                    $discounted_filter
                    $visible_filter
                    $features_filter ";
и обновляем его с учетом нашего нового фильтра
Код:
        $query = "SELECT count(distinct p.id) as count
                FROM __products AS p
                $category_id_filter
                WHERE 1
                    $brand_id_filter
                    $product_id_filter
                    $keyword_filter
            $is_new_filter
                    $is_featured_filter
                    $in_stock_filter
                    $discounted_filter
                    $visible_filter
                    $features_filter ";
10 - продолжаем ломать апи и ищем строку
Код:
public function get_product($id)
рядом с ней должен быть SQL запрос
Код:
        $query = "SELECT DISTINCT
                    p.id,
                    p.url,
                    p.brand_id,
                    p.name,
                    p.annotation,
                    p.body,
                    p.position,
                    p.created as created,
                    p.visible,
                    p.featured,
                    p.meta_title,
                    p.meta_keywords,
                    p.meta_description
                FROM __products AS p
                WHERE $filter
                GROUP BY p.id
                LIMIT 1";
и обновляем его с учетом нашего нового фильтра
Код:
        $query = "SELECT DISTINCT
                    p.id,
                    p.url,
                    p.brand_id,
                    p.name,
                    p.annotation,
                    p.body,
                    p.position,
                    p.created as created,
                    p.visible,
p.is_new,
                    p.featured,
                    p.meta_title,
                    p.meta_keywords,
                    p.meta_description
                FROM __products AS p
                WHERE $filter
                GROUP BY p.id
                LIMIT 1";
с этим файлом все, сохраняем и закрываем

11 - открываем view/View.php, и ищем
Код:
            $this->design->smarty->registerPlugin("function", "get_featured_products",        array($this, 'get_featured_products_plugin'));
после или перед, как удобно добавляем наш плагин
Код:
$this->design->smarty->registerPlugin("function", "get_is_new_products",   array($this, 'get_is_new_products_plugin'));
11 - в этом же файле ищем
Код:
    public function get_featured_products_plugin($params, &$smarty)
и перед этим вставляем код
Код:
public function get_is_new_products_plugin($params, &$smarty)
    {
        if(!isset($params['visible']))
            $params['visible'] = 1;
        $params['is_new'] = 1;
        if(!empty($params['var']))
        {
            foreach($this->products->get_products($params) as $p)
                $products[$p->id] = $p;

            if(!empty($products))
            {
                // id выбраных товаров
                $products_ids = array_keys($products);
  
                // Выбираем варианты товаров
                $variants = $this->variants->get_variants(array('product_id'=>$products_ids, 'in_stock'=>true));
          
                // Для каждого варианта
                foreach($variants as &$variant)
                {
                    // добавляем вариант в соответствующий товар
                    $products[$variant->product_id]->variants[] = $variant;
                }
          
                // Выбираем изображения товаров
                $images = $this->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];
                }          
            }

            $smarty->assign($params['var'], $products);
      
        }
    }

12 - Далее слова от автора
Теперь осталось получить и обработать данные в шаблоне. Открываем файл design/[ваш_шаблон]/html/main.tpl и вместо виджета get_new_products вызываем виджет

73
{get_is_new_products var=new_products limit=3}
Теперь мы получаем в "Новинки" не последние по дате добавления, а те товары, где мы поставили галочку "Новинка".

Как уже писало выше - вывести метку или поставить картинку в товаре, и в списке, и в карточке, Вы можете используя аналог следующего кода

1
{if $product->is_new}Новинка{/if}
Вот и все. По аналогии можно сделать и "Товар дня", и другой чекбокс для товара. Именно так и работает этот функционал на данном сайте :) можете проверить на главной.

Для общего понимания, это более разжеванная инструкция авторской статьи
Скрытое содержимое доступно для зарегистрированных пользователей!


Помогло? Залайкай! Засимпатируй =))))
 
Последнее редактирование:
Назад
Сверху Снизу