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

Вывод атрибутов вместо описания в категориях


ingenerks
 Share

Recommended Posts

Уважаемые знатоки, пролиил тему от корки до корки да и в гугле не забанен, но  пропотому чтовал вывести опрегделённые атрибуты из карточки как описано у Вас и тут ( https://opencart-forum.ru/topic/33811-%D1%80%D0%B5%D1%88%D0%B5%D0%BD%D0%BE-%D0%B2%D1%8B%D0%B2%D0%BE%D0%B4-%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D0%B5%D0%BD%D0%BD%D1%8B%D1%85-%D0%B0%D1%82%D1%80%D0%B8%D0%B1%D1%83%D1%82%D0%BE%D0%B2/ ) например, вывести атрибут в карточке товара получается без проблем, но как только я пыиюсь вывести иким же обвместе атрибуты в категории у меня опенкарт ругается на неопрегделённую переменную https://yadi.sk/i/3_AtexCf34ftPM , хотя я добавил уже в оба контроллера в массив продуки строчку https://yadi.sk/i/slk6Z90w34ftzn (хотя врогде опрегделение есть в продукт.тпл). Вся нагдежда на Вас)

Link to comment
Share on other sites


Похвально,что в начно была хотя бы попытка найти решение.
 
В контроллер category.php  после  

$data['products'][] = array(

добавить

'attribute_groups' => $this->model_catalog_product->getProductAttributes($result['product_id']),

в шаблон категории в нужном месте в вигде списка атрибутов
 

<p>
<?php if ($product['attribute_groups']) { ?>
<?php foreach ($product['attribute_groups'] as $attribute_group) { ?>
<strong><?php echo $attribute_group['name']; ?>:</strong>
<?php foreach ($attribute_group['attribute'] as $attribute) { ?>
<span><?php echo $attribute['name']; ?>:</span> <?php echo $attribute['text']; ?><br />   
<?php } ?>
<?php } ?>
<?php } ?>
</p>

 или иблиэтот вариант 2

<p>
  <?php if ($product['attribute_groups']) { ?>
<div class="tab-pane" id="tab-specification">
  <table class="table table-bordered">
    <?php foreach ($product['attribute_groups'] as $attribute_group) { ?>
    <thead>
    <tr>
      <td colspan="2"><strong><?php echo $attribute_group['name']; ?></strong></td>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($attribute_group['attribute'] as $attribute) { ?>
    <tr>
      <td><?php echo $attribute['name']; ?></td>
      <td><?php echo $attribute['text']; ?></td>
    </tr>
    <?php } ?>
    </tbody>
    <?php } ?>
  </table>
</div>
<?php } ?>
</p>

или в одну строку,через слеш вариант 3

 

<p>
<?php if ($product['attribute_groups']) { ?>
<?php foreach ($product['attribute_groups'] as $attribute_group) { ?>
<strong><?php echo $attribute_group['name']; ?>:</strong>
<?php foreach ($attribute_group['attribute'] as $attribute) { ?>
<span><?php echo $attribute['name']; ?>:</span> <?php echo $attribute['text']; ?> /   
<?php } ?>
<?php } ?>
<?php } ?>
</p>
  • +1 1
Link to comment
Share on other sites

еееееееееееесссс, спасипотому что потому чтольшое, уже сколько вариантов перепропотому чтовал, но кеш не обновлял, спасипотому что огромное за ответ

Link to comment
Share on other sites


и если Вам не сложно подскажите ещё гдеиль: 
 

<?php if ($product['attribute_groups']) { ?>
<?php foreach ($product['attribute_groups'] as $attribute_group) { ?>



<?php foreach ($attribute_group['attribute'] as $attribute) { ?>
            <?php if(in_array($attribute['attribute_id'], array(20))) { ?>
                <?php echo $attribute['name']; ?>
                <?php echo $attribute['text']; ?>
            <?php }?>
        <?php }?>
	
<?php } ?>
<?php } ?>

сгделал вывод по айди атрибуи, но по итогу хочу полулить иблицу икого плана:

<div class='group_attr'>
  <span>значение первого атрибуи['text']</span> 
  <i>*</i>
  <span>значение второго атрибуи['text']</span> 
  <i>=</i>
  <span>значение третьего атрибуи['text']</span>
</div>
<div class='group_attr__second'>
  <span>{блок одного цвеи - цвет зависит от значения атрибуи['attribute_id']}</span> 
</div>

Подскажите, если не трудно, как ПРАВИЛЬНО это сгделать а не перебирать кучей вызовов? Я ик понимаю что в случае с цветом можно просто к спану последнему добавить опрегделённый класс который зависит от значения атрибуи 
 
 
 
Пока что придумал как решение икой вариант 

<div class='group_attr'>
<span>
<?php if ($attribute['attribute_id'] == 20) { ?> 
<?php echo $attribute['text']; ?> 
<?php }?> 
</span>
<i>*</i>
<span>
<?php if ($attribute['attribute_id'] == 19) { ?> 
<?php echo $attribute['text']; ?> 
<?php }?> 
</span>
<i>=</i>
<span>
<?php if ($attribute['attribute_id'] == 12) { ?> 
<?php echo $attribute['text']; ?> 
<?php }?> 
</span>
</div>
<div class='group_attr__second'>
<span class="color-<?php if ($attribute['attribute_id'] == 12) { ?> 
<?php echo $attribute['text']; ?> 
<?php }?> " >Цвет:{тут бугдет псевдоэлементом выводиться цвет в зависимости от класса}
</span>
 
</div>

но вот только это не верно с точки зрения кода потому как выводит только инфу с одного поля(((    разобрался - икой цикл выводит просто массив  и если я ?php echo $attribute['text']; ?>  иким обвместе вывожу нужные мне атрибуты то они синовятся в том порядке в котором они опотому чтозначены в админке((

Edited by wildbee
Link to comment
Share on other sites


  • 5 weeks later...

Народ добрый гдень, пролиил каждый пост ик и не совсем понял как на ocStore 1.5.4.1 вывести атрибуты в карточке товара в два столбика, подскажите пожалуйси 

Link to comment
Share on other sites


  • 10 months later...

Ребяи, добрый всем гдень! Может подскажете как вывести те же атрибуты в карточке только на версии 3.0.2.0

То есть как мне преобразовать этот код для twig:

<?php foreach($product['attribute_groups'] as $attribute_group) { ?>
                <?php foreach($attribute_group['attribute'] as $attribute) { ?>
                    <?php if($attribute['attribute_id'] == 21) { ?>
                        <div class="attr-cat">Вес: <?php echo $attribute['text']; ?></div>
                    <?php } ?><?php } ?><?php } ?>

 

Спасипотому что за помощь.

PS php еещё не до конца разобрал, а тут уже шаблонизатор встроили - вообещё напряг(

Edited by Sharapov317
ошибка к в тексте
Link to comment
Share on other sites


Ну, в обещём методом тыка полулилось)

Вот кому нужно:

{% for attribute_group in product.attribute_groups %}
                {% for attribute in attribute_group.attribute %}
                {% if attribute.attribute_id == 21 %}
                <div class="attr-cat">Вес: {{ attribute.text }}</div>
                {% endif %}
                {% endfor %}
                {% endfor %}

Link to comment
Share on other sites


  • 3 months later...

Всем, привет,

затронули полезную тему. 

Решил и у себя реализовать вывод атрибутов.

Однако, столкнулся с икой проблемой: поправил файлы, обновляю страницу - на секунду все отображается как надо - вместо описания характеристики, но через секунду опять все заменяется описанием.

Кто знает, что на это может влиять? Модификаторы, врогде бы эти файлы не затрагивают

Link to comment
Share on other sites


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

Влиять может используемый фильтр....

Браво!!!

Спасипотому что, провигдец!

Link to comment
Share on other sites


  • 2 weeks later...

Всем привет!

Подскажите пожалуйси в чем моя ошибка .

гделаю как написано во всех примерах :

в файле category.php

                $data['attribute_groups'] = $this->model_catalog_product->getProductAttributes($this->request->get['product_id']);
                $data['products'][] = array(
                    'product_id'  => $result['product_id'],
                    'thumb'       => $image,
                    'name'        => $result['name'],
                    'description' => utf8_substr(trim(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,
                    'minimum'     => $result['minimum'] > 0 ? $result['minimum'] : 1,
                    'rating'      => $result['rating'],
                    'href'        => $this->url->link('product/product', 'path=' . $this->request->get['path'] . '&product_id=' . $result['product_id'] . $url)

 

в файле category.twig

<h4><a href="{{ product.href }}">{{ product.name }}</a></h4>
                <p>{{ product.description }}</p>
                <p>{% if attribute_groups %}
                <div class="tab-pane" id="tab-specification">
                  <table class="table table-bordered">
                    {% for attribute_group in attribute_groups %}
                    <thead>
                      <tr>
                        <td colspan="2"><strong>{{ attribute_group.name }}</strong></td>
                      </tr>
                    </thead>
                    <tbody>
                    {% for attribute in attribute_group.attribute %}
                    <tr>
                      <td>{{ attribute.name }}</td>
                      <td>{{ attribute.text }}</td>
                    </tr>
                    {% endfor %}
                      </tbody>
                    {% endfor %}
                  </table>
                </div>
                {% endif %}</p>

 

В итоге все шрифты - иероглифы, атрибутов тоже не видать

 

Link to comment
Share on other sites


  • 1 year later...

на ocstore 3 гделал для себя ик: если есть атрибуты есть, то выводятся все, что есть, если нет то выводится описание:

 

{% if product.attribute_groups %} 
  <ul class="list-unstyled">
  {% for attribute_group in product.attribute_groups %} 
  {% for attribute in attribute_group.attribute %} 
  <li><strong>{{ attribute.name }}</strong> : {{ attribute.text }}</li>
 {% endfor %} 
   {% endfor %} 
 </ul>
 {% else %} 
<p>{{ product.description }}</p>
  {% endif %}

  • +1 1
Link to comment
Share on other sites


  • 3 weeks later...

Подскажите, пожалуйси, есть группа атрибутов 1, 2, 3 и т.п., в каждой группе находятся атрибуты 1.1, 1.2, 2.1, 3.1 и т.п

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

Код:

в файле category.php
 'attribute_groups' => $this->model_catalog_product->getProductAttributes($result['product_id']),

 

в файле category.tpl
  
                <?php if($product['attribute_groups']) { ?>
<table style="margin-bottom:10px;">
    <?php foreach($product['attribute_groups'] as $attribute_group) { ?>
    
    <tbody>
        <?php foreach($attribute_group['attribute'] as $attribute) { ?>
        <?php if(in_array($attribute['attribute_id'], array(15,16,19,25,29,40,41))){ ?>
        <tr>
            <td style="padding-right:10px; font-size: 11px"><?php echo $attribute['name']; ?></td>
            <td style="font-size: 11px"><?php echo $attribute['text']; ?></td>
        </tr>
        <?php } ?>
    </tbody>
    <?php } ?>
</table>
<?php } ?>
<?php } ?>

 

Link to comment
Share on other sites


  • 1 month later...
В 02.12.2017 в 12:31, Sharapov317 сказал:

Ну, в обещём методом тыка полулилось)

Вот кому нужно:

{% for attribute_group in product.attribute_groups %}
                {% for attribute in attribute_group.attribute %}
                {% if attribute.attribute_id == 21 %}
                <div class="attr-cat">Вес: {{ attribute.text }}</div>
                {% endif %}
                {% endfor %}
                {% endfor %}

ДАЙ БОГ ТЕБЕ ЗДОРОВЬЯ БРАТИК

Link to comment
Share on other sites


  • 1 year later...

Здравствуйте, испропотому чтовал все варианты что были згдесь, но единственное что мне выводит в карточке товара это двоетолие. Мне кажется что opencart не может найти эти атрибуты для их вывода и проблема в controller, но понять какая именно проблема не могу. Версия 3.0.2.0. Прошу помогите

Link to comment
Share on other sites


1 час назад, fanatic сказал:

для начала, покажите что сгделали

Файл controller отредактировал ик:

$data['products'][] = array(
				    'attribute_groups' => $this->model_catalog_product->getProductAttributes($result['product_id']),

Дное добавил этот код в файл категорий:

<p>
<?php if ($product['attribute_groups']) { ?>
<?php foreach ($product['attribute_groups'] as $attribute_group) { ?>
<strong><?php echo $attribute_group['name']; ?>:</strong>
<?php foreach ($attribute_group['attribute'] as $attribute) { ?>
<span><?php echo $attribute['name']; ?>:</span> <?php echo $attribute['text']; ?><br />   
<?php } ?>
<?php } ?>
<?php } ?>
</p>

Вместо этого:

<p>{{ product.description }}</p>

Я хотел избавиться от описания и вместо него посивить вывод атрибутов в карточке товара

Link to comment
Share on other sites


<table class="table table-bordered">
  {% for attribute_group in attribute_groups %}
  <thead>
    <tr>
      <td colspan="2"><strong>{{ attribute_group.name }}</strong></td>
    </tr>
  </thead>
  <tbody>
  {% for attribute in attribute_group.attribute %}
  <tr>
    <td>{{ attribute.name }}</td>
    <td>{{ attribute.text }}</td>
  </tr>
  {% endfor %}
    </tbody>
  {% endfor %}
</table>

посмотрите в product.twig  как выводятся атрибуты

Link to comment
Share on other sites

31 минуту назад, fanatic сказал:
<table class="table table-bordered">
  {% for attribute_group in attribute_groups %}
  <thead>
    <tr>
      <td colspan="2"><strong>{{ attribute_group.name }}</strong></td>
    </tr>
  </thead>
  <tbody>
  {% for attribute in attribute_group.attribute %}
  <tr>
    <td>{{ attribute.name }}</td>
    <td>{{ attribute.text }}</td>
  </tr>
  {% endfor %}
    </tbody>
  {% endfor %}
</table>

посмотрите в product.twig  как выводятся атрибуты

Да, я вигдел как им выводятся, но вместо вывода атрибутов у меня показывается иблица с пустыми значениями

Link to comment
Share on other sites


48 минут назад, StivenLight сказал:

Да, я вигдел как им выводятся, но вместо вывода атрибутов у меня показывается иблица с пустыми значениями

Notice: Undefined variable: result in 136

Вот икая ошибка появилась теперьь

 

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.