Jump to content

Recommended Posts

Hello,

We are using prestashop 8.0.4, and Warehouse Theme

We want to show, at the start of every combination name, the reference of that combination.

We tried to display the var. $product.reference_to_display there but that only shows the active combination reference

Here we tried to edit it, inside product-variants.tpl file, but we cant figure out wich variable is the correct, if there's one

{foreach from=$group.attributes key=id_attribute item=group_attribute}
                        <li class="input-container float-left {if $group.attributes_quantity.$id_attribute <= 0} attribute-not-in-stock{/if}">
                            <input class="input-radio" type="radio" data-product-attribute="{$id_attribute_group}"
                                   name="group[{$id_attribute_group}]"
                                   title="{$group_attribute.name}"
                                   value="{$id_attribute}"{if $group_attribute.selected} checked="checked"{/if}>
                            <span class="radio-label">{combination reference} - {$group_attribute.name}</span>
                        </li>
{/foreach}

Thanks in advance

Link to comment
Share on other sites

2 godziny temu, tecniconivelz napisał:

Hello,

We are using prestashop 8.0.4, and Warehouse Theme

We want to show, at the start of every combination name, the reference of that combination.

We tried to display the var. $product.reference_to_display there but that only shows the active combination reference

Here we tried to edit it, inside product-variants.tpl file, but we cant figure out wich variable is the correct, if there's one

{foreach from=$group.attributes key=id_attribute item=group_attribute}
                        <li class="input-container float-left {if $group.attributes_quantity.$id_attribute <= 0} attribute-not-in-stock{/if}">
                            <input class="input-radio" type="radio" data-product-attribute="{$id_attribute_group}"
                                   name="group[{$id_attribute_group}]"
                                   title="{$group_attribute.name}"
                                   value="{$id_attribute}"{if $group_attribute.selected} checked="checked"{/if}>
                            <span class="radio-label">{combination reference} - {$group_attribute.name}</span>
                        </li>
{/foreach}

Thanks in advance

Product variants only display name of attribute groups and attribute name. References are not assigned in that variable. Also references are updated on combination change trough ajax call. You will have to edit ProductController so it provides combination references on product page load.
You can do it in two ways.

override product controller function getTemplateVarProduct or some getAttributesGroup function, so it adds references to the group.
Create module and use hookfilterProductContent to do the same but assign them to product object before it's presented to the user.

  • Like 1
Link to comment
Share on other sites

Hi.

It's easier than it seems.

Every time you change the combination, the reference changes as well.

1. a function needs to be added to ./classes/Combination.php

public static function getReferenceById($idProductAttribute)
    {
        if (empty($idProductAttribute)) {
            return;
        }

        $query = new DbQuery();
        $query->select('pa.reference');
        $query->from('product_attribute', 'pa');
        $query->where('pa.id_product_attribute = \'' . pSQL($idProductAttribute) . '\'');

        return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query);
    }

2. in your template product-variants.tpl you insert the code at the beginning

I intentionally left the attribute ID there before the reference to make it understandable for others.

Ref: {$product.id_product_attribute} - {Combination::getReferenceById($product.id_product_attribute)}

obrazek.thumb.png.2bc5d7aa397c6efeb53453ba475c1c0e.png

 

3.  result

obrazek.png.19183df728985699552547b06c069a08.png

Edited by ps8moduly.cz (see edit history)
Link to comment
Share on other sites

3 godziny temu, tecniconivelz napisał:

Hello,

Thanks for the help, the first option would be the ideal, but im kinda lost there, what do I have to modify to be able to render the combination references?

 

You will have to override protected function assignAttributesGroups inside ProductController.php and add below line of code at the end of foreach loop. 

//assign reference to each attribute
$groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']]['reference'] = $row['reference'];

Then you will be able to access variable inside product-variants.tpl by calling it {$group_attribute.reference}

{foreach from=$group.attributes key=id_attribute item=group_attribute}
<option value="{$id_attribute}" title="{$group_attribute.name}"{if $group_attribute.selected} selected="selected"{/if}>{$group_attribute.reference} {$group_attribute.name}</option>
{/foreach}

Here you can see what it looks like:
Untitled.jpg.e8bd23f7ec25b3114400c2590c51478f.jpg

Tested it on version 1.7.8, but should work on 8 aswell. Let us know if you need help creating override. Because if you just modify file directly it will be replaced after you upgrade prestashop to higher version. With override you can keep your modifications.
 

 

Here is entire function so you can navigate easier while you edit yours:

   protected function assignAttributesGroups($product_for_template = null)
    {
        $colors = [];
        $groups = [];
        $this->combinations = [];

        /** @todo (RM) should only get groups and not all declination ? */
        $attributes_groups = $this->product->getAttributesGroups($this->context->language->id);
        if (is_array($attributes_groups) && $attributes_groups) {
            $combination_images = $this->product->getCombinationImages($this->context->language->id);
            $combination_prices_set = [];
            foreach ($attributes_groups as $k => $row) {
                // Color management
                if (isset($row['is_color_group']) && $row['is_color_group'] && (isset($row['attribute_color']) && $row['attribute_color']) || (file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg'))) {
                    $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                    $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                    if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {
                        $colors[$row['id_attribute']]['attributes_quantity'] = 0;
                    }
                    $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];
                }
                if (!isset($groups[$row['id_attribute_group']])) {
                    $groups[$row['id_attribute_group']] = [
                        'group_name' => $row['group_name'],
                        'name' => $row['public_group_name'],
                        'group_type' => $row['group_type'],
                        'default' => -1,
                    ];
                }

                $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = [
                    'name' => $row['attribute_name'],
                    'html_color_code' => $row['attribute_color'],
                    'texture' => (@filemtime(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) ? _THEME_COL_DIR_ . $row['id_attribute'] . '.jpg' : '',
                    'selected' => (isset($product_for_template['attributes'][$row['id_attribute_group']]['id_attribute']) && $product_for_template['attributes'][$row['id_attribute_group']]['id_attribute'] == $row['id_attribute']) ? true : false,
                ];

                //$product.attributes.$id_attribute_group.id_attribute eq $id_attribute
                if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {
                    $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];
                }
                if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                    $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
                }
                $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];
                $this->combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
                $this->combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];
                $this->combinations[$row['id_product_attribute']]['price'] = (float) $row['price'];

                // Call getPriceStatic in order to set $combination_specific_price
                if (!isset($combination_prices_set[(int) $row['id_product_attribute']])) {
                    $combination_specific_price = null;
                    Product::getPriceStatic((int) $this->product->id, false, $row['id_product_attribute'], 6, null, false, true, 1, false, null, null, null, $combination_specific_price);
                    $combination_prices_set[(int) $row['id_product_attribute']] = true;
                    $this->combinations[$row['id_product_attribute']]['specific_price'] = $combination_specific_price;
                }
                $this->combinations[$row['id_product_attribute']]['ecotax'] = (float) $row['ecotax'];
                $this->combinations[$row['id_product_attribute']]['weight'] = (float) $row['weight'];
                $this->combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];
                $this->combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
                $this->combinations[$row['id_product_attribute']]['ean13'] = $row['ean13'];
                $this->combinations[$row['id_product_attribute']]['mpn'] = $row['mpn'];
                $this->combinations[$row['id_product_attribute']]['upc'] = $row['upc'];
                $this->combinations[$row['id_product_attribute']]['isbn'] = $row['isbn'];
                $this->combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact'];
                $this->combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
                if ($row['available_date'] != '0000-00-00' && Validate::isDate($row['available_date'])) {
                    $this->combinations[$row['id_product_attribute']]['available_date'] = $row['available_date'];
                    $this->combinations[$row['id_product_attribute']]['date_formatted'] = Tools::displayDate($row['available_date']);
                } else {
                    $this->combinations[$row['id_product_attribute']]['available_date'] = $this->combinations[$row['id_product_attribute']]['date_formatted'] = '';
                }

                if (!isset($combination_images[$row['id_product_attribute']][0]['id_image'])) {
                    $this->combinations[$row['id_product_attribute']]['id_image'] = -1;
                } else {
                    $this->combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $combination_images[$row['id_product_attribute']][0]['id_image'];
                    if ($row['default_on']) {
                        foreach ($this->context->smarty->tpl_vars['product']->value['images'] as $image) {
                            if ($image['cover'] == 1) {
                                $current_cover = $image;
                            }
                        }
                        if (!isset($current_cover)) {
                            $current_cover = array_values($this->context->smarty->tpl_vars['product']->value['images'])[0];
                        }

                        if (is_array($combination_images[$row['id_product_attribute']])) {
                            foreach ($combination_images[$row['id_product_attribute']] as $tmp) {
                                if ($tmp['id_image'] == $current_cover['id_image']) {
                                    $this->combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $tmp['id_image'];

                                    break;
                                }
                            }
                        }

                        if ($id_image > 0) {
                            if (isset($this->context->smarty->tpl_vars['images']->value)) {
                                $product_images = $this->context->smarty->tpl_vars['images']->value;
                            }
                            if (isset($product_images) && is_array($product_images) && isset($product_images[$id_image])) {
                                $product_images[$id_image]['cover'] = 1;
                                $this->context->smarty->assign('mainImage', $product_images[$id_image]);
                                if (count($product_images)) {
                                    $this->context->smarty->assign('images', $product_images);
                                }
                            }

                            $cover = $current_cover;

                            if (isset($cover) && is_array($cover) && isset($product_images) && is_array($product_images)) {
                                $product_images[$cover['id_image']]['cover'] = 0;
                                if (isset($product_images[$id_image])) {
                                    $cover = $product_images[$id_image];
                                }
                                $cover['id_image'] = (Configuration::get('PS_LEGACY_IMAGES') ? ($this->product->id . '-' . $id_image) : (int) $id_image);
                                $cover['id_image_only'] = (int) $id_image;
                                $this->context->smarty->assign('cover', $cover);
                            }
                        }
                    }
                }
				//assign reference to each attribute
				$groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']]['reference'] = $row['reference'];				
            }

            // wash attributes list depending on available attributes depending on selected preceding attributes
            $current_selected_attributes = [];
            $count = 0;
            foreach ($groups as &$group) {
                ++$count;
                if ($count > 1) {
                    //find attributes of current group, having a possible combination with current selected
                    $id_product_attributes = [0];
                    $query = 'SELECT pac.`id_product_attribute`
                        FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac
                        INNER JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.id_product_attribute = pac.id_product_attribute
                        WHERE id_product = ' . $this->product->id . ' AND id_attribute IN (' . implode(',', array_map('intval', $current_selected_attributes)) . ')
                        GROUP BY id_product_attribute
                        HAVING COUNT(id_product) = ' . count($current_selected_attributes);
                    if ($results = Db::getInstance()->executeS($query)) {
                        foreach ($results as $row) {
                            $id_product_attributes[] = $row['id_product_attribute'];
                        }
                    }
                    $id_attributes = Db::getInstance()->executeS('SELECT pac2.`id_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac2' .
                        ((!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && 0 == Configuration::get('PS_DISP_UNAVAILABLE_ATTR')) ?
                        ' INNER JOIN `' . _DB_PREFIX_ . 'stock_available` pa ON pa.id_product_attribute = pac2.id_product_attribute
                        WHERE pa.quantity > 0 AND ' :
                        ' WHERE ') .
                        'pac2.`id_product_attribute` IN (' . implode(',', array_map('intval', $id_product_attributes)) . ')
                        AND pac2.id_attribute NOT IN (' . implode(',', array_map('intval', $current_selected_attributes)) . ')');
                    foreach ($id_attributes as $k => $row) {
                        $id_attributes[$k] = (int) $row['id_attribute'];
                    }
                    foreach ($group['attributes'] as $key => $attribute) {
                        if (!in_array((int) $key, $id_attributes)) {
                            unset(
                                $group['attributes'][$key],
                                $group['attributes_quantity'][$key]
                            );
                        }
                    }
                }
                //find selected attribute or first of group
                $index = 0;
                $current_selected_attribute = 0;
                foreach ($group['attributes'] as $key => $attribute) {
                    if ($index === 0) {
                        $current_selected_attribute = $key;
                    }
                    if ($attribute['selected']) {
                        $current_selected_attribute = $key;

                        break;
                    }
                }
                if ($current_selected_attribute > 0) {
                    $current_selected_attributes[] = $current_selected_attribute;
                }
            }

            // wash attributes list (if some attributes are unavailables and if allowed to wash it)
            if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {
                foreach ($groups as &$group) {
                    foreach ($group['attributes_quantity'] as $key => $quantity) {
                        if ($quantity <= 0) {
                            unset($group['attributes'][$key]);
                        }
                    }
                }

                foreach ($colors as $key => $color) {
                    if ($color['attributes_quantity'] <= 0) {
                        unset($colors[$key]);
                    }
                }
            }
            foreach ($this->combinations as $id_product_attribute => $comb) {
                $attribute_list = '';
                foreach ($comb['attributes'] as $id_attribute) {
                    $attribute_list .= '\'' . (int) $id_attribute . '\',';
                }
                $attribute_list = rtrim($attribute_list, ',');
                $this->combinations[$id_product_attribute]['list'] = $attribute_list;
            }
            unset($group);

            $this->context->smarty->assign([
                'groups' => $groups,
                'colors' => (count($colors)) ? $colors : false,
                'combinations' => $this->combinations,
                'combinationImages' => $combination_images,
            ]);
        } else {
            $this->context->smarty->assign([
                'groups' => [],
                'colors' => false,
                'combinations' => [],
                'combinationImages' => [],
            ]);
        }
    }
Edited by WisQQ (see edit history)
  • Thanks 1
Link to comment
Share on other sites

2 godziny temu, ps8moduly.cz napisał:

Hi.

It's easier than it seems.

Every time you change the combination, the reference changes as well.

1. a function needs to be added to ./classes/Combination.php

public static function getReferenceById($idProductAttribute)
    {
        if (empty($idProductAttribute)) {
            return;
        }

        $query = new DbQuery();
        $query->select('pa.reference');
        $query->from('product_attribute', 'pa');
        $query->where('pa.id_product_attribute = \'' . pSQL($idProductAttribute) . '\'');

        return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query);
    }

2. in your template product-variants.tpl you insert the code at the beginning

I intentionally left the attribute ID there before the reference to make it understandable for others.

Ref: {$product.id_product_attribute} - {Combination::getReferenceById($product.id_product_attribute)}

obrazek.thumb.png.2bc5d7aa397c6efeb53453ba475c1c0e.png

 

3.  result

obrazek.png.19183df728985699552547b06c069a08.png

From what i understood the op wants to display reference near each attribute name. Solution you provided will only reload already loaded reference with extra database call. But it's a nice way of adding functionality with static class. :)

  • Haha 1
Link to comment
Share on other sites

On 1/12/2024 at 9:29 PM, WisQQ said:

You will have to override protected function assignAttributesGroups inside ProductController.php and add below line of code at the end of foreach loop. 

//assign reference to each attribute
$groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']]['reference'] = $row['reference'];

Then you will be able to access variable inside product-variants.tpl by calling it {$group_attribute.reference}

{foreach from=$group.attributes key=id_attribute item=group_attribute}
<option value="{$id_attribute}" title="{$group_attribute.name}"{if $group_attribute.selected} selected="selected"{/if}>{$group_attribute.reference} {$group_attribute.name}</option>
{/foreach}

Here you can see what it looks like:
Untitled.jpg.e8bd23f7ec25b3114400c2590c51478f.jpg

Tested it on version 1.7.8, but should work on 8 aswell. Let us know if you need help creating override. Because if you just modify file directly it will be replaced after you upgrade prestashop to higher version. With override you can keep your modifications.
 

 

Here is entire function so you can navigate easier while you edit yours:

   protected function assignAttributesGroups($product_for_template = null)
    {
        $colors = [];
        $groups = [];
        $this->combinations = [];

        /** @todo (RM) should only get groups and not all declination ? */
        $attributes_groups = $this->product->getAttributesGroups($this->context->language->id);
        if (is_array($attributes_groups) && $attributes_groups) {
            $combination_images = $this->product->getCombinationImages($this->context->language->id);
            $combination_prices_set = [];
            foreach ($attributes_groups as $k => $row) {
                // Color management
                if (isset($row['is_color_group']) && $row['is_color_group'] && (isset($row['attribute_color']) && $row['attribute_color']) || (file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg'))) {
                    $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                    $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                    if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {
                        $colors[$row['id_attribute']]['attributes_quantity'] = 0;
                    }
                    $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];
                }
                if (!isset($groups[$row['id_attribute_group']])) {
                    $groups[$row['id_attribute_group']] = [
                        'group_name' => $row['group_name'],
                        'name' => $row['public_group_name'],
                        'group_type' => $row['group_type'],
                        'default' => -1,
                    ];
                }

                $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = [
                    'name' => $row['attribute_name'],
                    'html_color_code' => $row['attribute_color'],
                    'texture' => (@filemtime(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) ? _THEME_COL_DIR_ . $row['id_attribute'] . '.jpg' : '',
                    'selected' => (isset($product_for_template['attributes'][$row['id_attribute_group']]['id_attribute']) && $product_for_template['attributes'][$row['id_attribute_group']]['id_attribute'] == $row['id_attribute']) ? true : false,
                ];

                //$product.attributes.$id_attribute_group.id_attribute eq $id_attribute
                if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {
                    $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];
                }
                if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                    $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
                }
                $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];
                $this->combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
                $this->combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];
                $this->combinations[$row['id_product_attribute']]['price'] = (float) $row['price'];

                // Call getPriceStatic in order to set $combination_specific_price
                if (!isset($combination_prices_set[(int) $row['id_product_attribute']])) {
                    $combination_specific_price = null;
                    Product::getPriceStatic((int) $this->product->id, false, $row['id_product_attribute'], 6, null, false, true, 1, false, null, null, null, $combination_specific_price);
                    $combination_prices_set[(int) $row['id_product_attribute']] = true;
                    $this->combinations[$row['id_product_attribute']]['specific_price'] = $combination_specific_price;
                }
                $this->combinations[$row['id_product_attribute']]['ecotax'] = (float) $row['ecotax'];
                $this->combinations[$row['id_product_attribute']]['weight'] = (float) $row['weight'];
                $this->combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];
                $this->combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
                $this->combinations[$row['id_product_attribute']]['ean13'] = $row['ean13'];
                $this->combinations[$row['id_product_attribute']]['mpn'] = $row['mpn'];
                $this->combinations[$row['id_product_attribute']]['upc'] = $row['upc'];
                $this->combinations[$row['id_product_attribute']]['isbn'] = $row['isbn'];
                $this->combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact'];
                $this->combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
                if ($row['available_date'] != '0000-00-00' && Validate::isDate($row['available_date'])) {
                    $this->combinations[$row['id_product_attribute']]['available_date'] = $row['available_date'];
                    $this->combinations[$row['id_product_attribute']]['date_formatted'] = Tools::displayDate($row['available_date']);
                } else {
                    $this->combinations[$row['id_product_attribute']]['available_date'] = $this->combinations[$row['id_product_attribute']]['date_formatted'] = '';
                }

                if (!isset($combination_images[$row['id_product_attribute']][0]['id_image'])) {
                    $this->combinations[$row['id_product_attribute']]['id_image'] = -1;
                } else {
                    $this->combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $combination_images[$row['id_product_attribute']][0]['id_image'];
                    if ($row['default_on']) {
                        foreach ($this->context->smarty->tpl_vars['product']->value['images'] as $image) {
                            if ($image['cover'] == 1) {
                                $current_cover = $image;
                            }
                        }
                        if (!isset($current_cover)) {
                            $current_cover = array_values($this->context->smarty->tpl_vars['product']->value['images'])[0];
                        }

                        if (is_array($combination_images[$row['id_product_attribute']])) {
                            foreach ($combination_images[$row['id_product_attribute']] as $tmp) {
                                if ($tmp['id_image'] == $current_cover['id_image']) {
                                    $this->combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $tmp['id_image'];

                                    break;
                                }
                            }
                        }

                        if ($id_image > 0) {
                            if (isset($this->context->smarty->tpl_vars['images']->value)) {
                                $product_images = $this->context->smarty->tpl_vars['images']->value;
                            }
                            if (isset($product_images) && is_array($product_images) && isset($product_images[$id_image])) {
                                $product_images[$id_image]['cover'] = 1;
                                $this->context->smarty->assign('mainImage', $product_images[$id_image]);
                                if (count($product_images)) {
                                    $this->context->smarty->assign('images', $product_images);
                                }
                            }

                            $cover = $current_cover;

                            if (isset($cover) && is_array($cover) && isset($product_images) && is_array($product_images)) {
                                $product_images[$cover['id_image']]['cover'] = 0;
                                if (isset($product_images[$id_image])) {
                                    $cover = $product_images[$id_image];
                                }
                                $cover['id_image'] = (Configuration::get('PS_LEGACY_IMAGES') ? ($this->product->id . '-' . $id_image) : (int) $id_image);
                                $cover['id_image_only'] = (int) $id_image;
                                $this->context->smarty->assign('cover', $cover);
                            }
                        }
                    }
                }
				//assign reference to each attribute
				$groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']]['reference'] = $row['reference'];				
            }

            // wash attributes list depending on available attributes depending on selected preceding attributes
            $current_selected_attributes = [];
            $count = 0;
            foreach ($groups as &$group) {
                ++$count;
                if ($count > 1) {
                    //find attributes of current group, having a possible combination with current selected
                    $id_product_attributes = [0];
                    $query = 'SELECT pac.`id_product_attribute`
                        FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac
                        INNER JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.id_product_attribute = pac.id_product_attribute
                        WHERE id_product = ' . $this->product->id . ' AND id_attribute IN (' . implode(',', array_map('intval', $current_selected_attributes)) . ')
                        GROUP BY id_product_attribute
                        HAVING COUNT(id_product) = ' . count($current_selected_attributes);
                    if ($results = Db::getInstance()->executeS($query)) {
                        foreach ($results as $row) {
                            $id_product_attributes[] = $row['id_product_attribute'];
                        }
                    }
                    $id_attributes = Db::getInstance()->executeS('SELECT pac2.`id_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac2' .
                        ((!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && 0 == Configuration::get('PS_DISP_UNAVAILABLE_ATTR')) ?
                        ' INNER JOIN `' . _DB_PREFIX_ . 'stock_available` pa ON pa.id_product_attribute = pac2.id_product_attribute
                        WHERE pa.quantity > 0 AND ' :
                        ' WHERE ') .
                        'pac2.`id_product_attribute` IN (' . implode(',', array_map('intval', $id_product_attributes)) . ')
                        AND pac2.id_attribute NOT IN (' . implode(',', array_map('intval', $current_selected_attributes)) . ')');
                    foreach ($id_attributes as $k => $row) {
                        $id_attributes[$k] = (int) $row['id_attribute'];
                    }
                    foreach ($group['attributes'] as $key => $attribute) {
                        if (!in_array((int) $key, $id_attributes)) {
                            unset(
                                $group['attributes'][$key],
                                $group['attributes_quantity'][$key]
                            );
                        }
                    }
                }
                //find selected attribute or first of group
                $index = 0;
                $current_selected_attribute = 0;
                foreach ($group['attributes'] as $key => $attribute) {
                    if ($index === 0) {
                        $current_selected_attribute = $key;
                    }
                    if ($attribute['selected']) {
                        $current_selected_attribute = $key;

                        break;
                    }
                }
                if ($current_selected_attribute > 0) {
                    $current_selected_attributes[] = $current_selected_attribute;
                }
            }

            // wash attributes list (if some attributes are unavailables and if allowed to wash it)
            if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {
                foreach ($groups as &$group) {
                    foreach ($group['attributes_quantity'] as $key => $quantity) {
                        if ($quantity <= 0) {
                            unset($group['attributes'][$key]);
                        }
                    }
                }

                foreach ($colors as $key => $color) {
                    if ($color['attributes_quantity'] <= 0) {
                        unset($colors[$key]);
                    }
                }
            }
            foreach ($this->combinations as $id_product_attribute => $comb) {
                $attribute_list = '';
                foreach ($comb['attributes'] as $id_attribute) {
                    $attribute_list .= '\'' . (int) $id_attribute . '\',';
                }
                $attribute_list = rtrim($attribute_list, ',');
                $this->combinations[$id_product_attribute]['list'] = $attribute_list;
            }
            unset($group);

            $this->context->smarty->assign([
                'groups' => $groups,
                'colors' => (count($colors)) ? $colors : false,
                'combinations' => $this->combinations,
                'combinationImages' => $combination_images,
            ]);
        } else {
            $this->context->smarty->assign([
                'groups' => [],
                'colors' => false,
                'combinations' => [],
                'combinationImages' => [],
            ]);
        }
    }

Hello,

Thanks, thats exactly what we needed!

I tried it first in the main ProducController.php, and it works

Now in the override, I've extended the class ProductControllerCore, and added the assignAttributesGroups function, but doesnt seem to work, pretty much Im missing something

 

<?php

class ProductController extends ProductControllerCore
{
    /**
     * Assign template vars related to attribute groups and colors.
     */
    protected function assignAttributesGroups($product_for_template = null)
    {
        $colors = [];
        $groups = [];
        $this->combinations = [];

        /** @todo (RM) should only get groups and not all declination ? */
        $attributes_groups = $this->product->getAttributesGroups($this->context->language->id);
        if (is_array($attributes_groups) && $attributes_groups) {
            $combination_images = $this->product->getCombinationImages($this->context->language->id);
            $combination_prices_set = [];
            foreach ($attributes_groups as $k => $row) {
                // Color management
                if (isset($row['is_color_group']) && $row['is_color_group'] && (isset($row['attribute_color']) && $row['attribute_color']) || (file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg'))) {
                    $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                    $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                    if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {
                        $colors[$row['id_attribute']]['attributes_quantity'] = 0;
                    }
                    $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];
                }
                if (!isset($groups[$row['id_attribute_group']])) {
                    $groups[$row['id_attribute_group']] = [
                        'group_name' => $row['group_name'],
                        'name' => $row['public_group_name'],
                        'group_type' => $row['group_type'],
                        'default' => -1,
                    ];
                }

                $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = [
                    'name' => $row['attribute_name'],
                    'html_color_code' => $row['attribute_color'],
                    'texture' => (@filemtime(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) ? _THEME_COL_DIR_ . $row['id_attribute'] . '.jpg' : '',
                    'selected' => (isset($product_for_template['attributes'][$row['id_attribute_group']]['id_attribute']) && $product_for_template['attributes'][$row['id_attribute_group']]['id_attribute'] == $row['id_attribute']) ? true : false,
                ];

                //$product.attributes.$id_attribute_group.id_attribute eq $id_attribute
                if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {
                    $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];
                }
                if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                    $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
                }
                $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];

                $this->combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
                $this->combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];
                $this->combinations[$row['id_product_attribute']]['price'] = (float) $row['price'];

                // Call getPriceStatic in order to set $combination_specific_price
                if (!isset($combination_prices_set[(int) $row['id_product_attribute']])) {
                    $combination_specific_price = null;
                    Product::getPriceStatic((int) $this->product->id, false, $row['id_product_attribute'], 6, null, false, true, 1, false, null, null, null, $combination_specific_price);
                    $combination_prices_set[(int) $row['id_product_attribute']] = true;
                    $this->combinations[$row['id_product_attribute']]['specific_price'] = $combination_specific_price;
                }
                $this->combinations[$row['id_product_attribute']]['ecotax'] = (float) $row['ecotax'];
                $this->combinations[$row['id_product_attribute']]['weight'] = (float) $row['weight'];
                $this->combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];
                $this->combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
                $this->combinations[$row['id_product_attribute']]['ean13'] = $row['ean13'];
                $this->combinations[$row['id_product_attribute']]['mpn'] = $row['mpn'];
                $this->combinations[$row['id_product_attribute']]['upc'] = $row['upc'];
                $this->combinations[$row['id_product_attribute']]['isbn'] = $row['isbn'];
                $this->combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact'];
                $this->combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
                if ($row['available_date'] != '0000-00-00' && Validate::isDate($row['available_date'])) {
                    $this->combinations[$row['id_product_attribute']]['available_date'] = $row['available_date'];
                    $this->combinations[$row['id_product_attribute']]['date_formatted'] = Tools::displayDate($row['available_date']);
                } else {
                    $this->combinations[$row['id_product_attribute']]['available_date'] = $this->combinations[$row['id_product_attribute']]['date_formatted'] = '';
                }

                if (!isset($combination_images[$row['id_product_attribute']][0]['id_image'])) {
                    $this->combinations[$row['id_product_attribute']]['id_image'] = -1;
                } else {
                    $this->combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $combination_images[$row['id_product_attribute']][0]['id_image'];
                    if ($row['default_on']) {
                        foreach ($this->context->smarty->tpl_vars['product']->value['images'] as $image) {
                            if ($image['cover'] == 1) {
                                $current_cover = $image;
                            }
                        }
                        if (!isset($current_cover)) {
                            $current_cover = array_values($this->context->smarty->tpl_vars['product']->value['images'])[0];
                        }

                        if (is_array($combination_images[$row['id_product_attribute']])) {
                            foreach ($combination_images[$row['id_product_attribute']] as $tmp) {
                                if ($tmp['id_image'] == $current_cover['id_image']) {
                                    $this->combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $tmp['id_image'];

                                    break;
                                }
                            }
                        }

                        if ($id_image > 0) {
                            if (isset($this->context->smarty->tpl_vars['images']->value)) {
                                $product_images = $this->context->smarty->tpl_vars['images']->value;
                            }
                            if (isset($product_images) && is_array($product_images) && isset($product_images[$id_image])) {
                                $product_images[$id_image]['cover'] = 1;
                                $this->context->smarty->assign('mainImage', $product_images[$id_image]);
                                $this->context->smarty->assign('images', $product_images);
                            }

                            $cover = $current_cover;

                            if (isset($cover) && is_array($cover) && isset($product_images) && is_array($product_images)) {
                                $product_images[$cover['id_image']]['cover'] = 0;
                                if (isset($product_images[$id_image])) {
                                    $cover = $product_images[$id_image];
                                }
                                $cover['id_image'] = (Configuration::get('PS_LEGACY_IMAGES') ? ($this->product->id . '-' . $id_image) : (int) $id_image);
                                $cover['id_image_only'] = (int) $id_image;
                                $this->context->smarty->assign('cover', $cover);
                            }
                        }
                    }
                }
            //assign reference to each attribute
            $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']]['reference'] = $row['reference'];
            }

            // wash attributes list depending on available attributes depending on selected preceding attributes
            $current_selected_attributes = [];
            $count = 0;
            foreach ($groups as &$group) {
                ++$count;
                if ($count > 1) {
                    //find attributes of current group, having a possible combination with current selected
                    $id_product_attributes = [0];
                    $query = 'SELECT pac.`id_product_attribute`
                        FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac
                        INNER JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.id_product_attribute = pac.id_product_attribute
                        WHERE id_product = ' . $this->product->id . ' AND id_attribute IN (' . implode(',', array_map('intval', $current_selected_attributes)) . ')
                        GROUP BY id_product_attribute
                        HAVING COUNT(id_product) = ' . count($current_selected_attributes);
                    if ($results = Db::getInstance()->executeS($query)) {
                        foreach ($results as $row) {
                            $id_product_attributes[] = $row['id_product_attribute'];
                        }
                    }
                    $id_attributes = Db::getInstance()->executeS('SELECT pac2.`id_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac2' .
                        ((!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && 0 == Configuration::get('PS_DISP_UNAVAILABLE_ATTR')) ?
                        ' INNER JOIN `' . _DB_PREFIX_ . 'stock_available` pa ON pa.id_product_attribute = pac2.id_product_attribute
                        WHERE pa.quantity > 0 AND ' :
                        ' WHERE ') .
                        'pac2.`id_product_attribute` IN (' . implode(',', array_map('intval', $id_product_attributes)) . ')
                        AND pac2.id_attribute NOT IN (' . implode(',', array_map('intval', $current_selected_attributes)) . ')');
                    foreach ($id_attributes as $k => $row) {
                        $id_attributes[$k] = (int) $row['id_attribute'];
                    }
                    foreach ($group['attributes'] as $key => $attribute) {
                        if (!in_array((int) $key, $id_attributes)) {
                            unset(
                                $group['attributes'][$key],
                                $group['attributes_quantity'][$key]
                            );
                        }
                    }
                }
                //find selected attribute or first of group
                $index = 0;
                $current_selected_attribute = 0;
                foreach ($group['attributes'] as $key => $attribute) {
                    if ($index === 0) {
                        $current_selected_attribute = $key;
                    }
                    if ($attribute['selected']) {
                        $current_selected_attribute = $key;

                        break;
                    }
                }
                if ($current_selected_attribute > 0) {
                    $current_selected_attributes[] = $current_selected_attribute;
                }
            }

            // wash attributes list (if some attributes are unavailables and if allowed to wash it)
            if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {
                foreach ($groups as &$group) {
                    foreach ($group['attributes_quantity'] as $key => $quantity) {
                        if ($quantity <= 0) {
                            unset($group['attributes'][$key]);
                        }
                    }
                }

                foreach ($colors as $key => $color) {
                    if ($color['attributes_quantity'] <= 0) {
                        unset($colors[$key]);
                    }
                }
            }
            foreach ($this->combinations as $id_product_attribute => $comb) {
                $attribute_list = '';
                foreach ($comb['attributes'] as $id_attribute) {
                    $attribute_list .= '\'' . (int) $id_attribute . '\',';
                }
                $attribute_list = rtrim($attribute_list, ',');
                $this->combinations[$id_product_attribute]['list'] = $attribute_list;
            }
            unset($group);

            $this->context->smarty->assign([
                'groups' => $groups,
                'colors' => (count($colors)) ? $colors : false,
                'combinations' => $this->combinations,
                'combinationImages' => $combination_images,
            ]);
        } else {
            $this->context->smarty->assign([
                'groups' => [],
                'colors' => false,
                'combinations' => [],
                'combinationImages' => [],
            ]);
        }
    }

}

?>

What Im doing wrong?

Link to comment
Share on other sites

4 godziny temu, tecniconivelz napisał:

Hello,

Thanks, thats exactly what we needed!

I tried it first in the main ProducController.php, and it works

Now in the override, I've extended the class ProductControllerCore, and added the assignAttributesGroups function, but doesnt seem to work, pretty much Im missing something

 

<?php

class ProductController extends ProductControllerCore
{
    /**
     * Assign template vars related to attribute groups and colors.
     */
    protected function assignAttributesGroups($product_for_template = null)
    {
        $colors = [];
        $groups = [];
        $this->combinations = [];

        /** @todo (RM) should only get groups and not all declination ? */
        $attributes_groups = $this->product->getAttributesGroups($this->context->language->id);
        if (is_array($attributes_groups) && $attributes_groups) {
            $combination_images = $this->product->getCombinationImages($this->context->language->id);
            $combination_prices_set = [];
            foreach ($attributes_groups as $k => $row) {
                // Color management
                if (isset($row['is_color_group']) && $row['is_color_group'] && (isset($row['attribute_color']) && $row['attribute_color']) || (file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg'))) {
                    $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                    $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                    if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {
                        $colors[$row['id_attribute']]['attributes_quantity'] = 0;
                    }
                    $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];
                }
                if (!isset($groups[$row['id_attribute_group']])) {
                    $groups[$row['id_attribute_group']] = [
                        'group_name' => $row['group_name'],
                        'name' => $row['public_group_name'],
                        'group_type' => $row['group_type'],
                        'default' => -1,
                    ];
                }

                $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = [
                    'name' => $row['attribute_name'],
                    'html_color_code' => $row['attribute_color'],
                    'texture' => (@filemtime(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) ? _THEME_COL_DIR_ . $row['id_attribute'] . '.jpg' : '',
                    'selected' => (isset($product_for_template['attributes'][$row['id_attribute_group']]['id_attribute']) && $product_for_template['attributes'][$row['id_attribute_group']]['id_attribute'] == $row['id_attribute']) ? true : false,
                ];

                //$product.attributes.$id_attribute_group.id_attribute eq $id_attribute
                if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {
                    $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];
                }
                if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                    $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
                }
                $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];

                $this->combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
                $this->combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];
                $this->combinations[$row['id_product_attribute']]['price'] = (float) $row['price'];

                // Call getPriceStatic in order to set $combination_specific_price
                if (!isset($combination_prices_set[(int) $row['id_product_attribute']])) {
                    $combination_specific_price = null;
                    Product::getPriceStatic((int) $this->product->id, false, $row['id_product_attribute'], 6, null, false, true, 1, false, null, null, null, $combination_specific_price);
                    $combination_prices_set[(int) $row['id_product_attribute']] = true;
                    $this->combinations[$row['id_product_attribute']]['specific_price'] = $combination_specific_price;
                }
                $this->combinations[$row['id_product_attribute']]['ecotax'] = (float) $row['ecotax'];
                $this->combinations[$row['id_product_attribute']]['weight'] = (float) $row['weight'];
                $this->combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];
                $this->combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
                $this->combinations[$row['id_product_attribute']]['ean13'] = $row['ean13'];
                $this->combinations[$row['id_product_attribute']]['mpn'] = $row['mpn'];
                $this->combinations[$row['id_product_attribute']]['upc'] = $row['upc'];
                $this->combinations[$row['id_product_attribute']]['isbn'] = $row['isbn'];
                $this->combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact'];
                $this->combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
                if ($row['available_date'] != '0000-00-00' && Validate::isDate($row['available_date'])) {
                    $this->combinations[$row['id_product_attribute']]['available_date'] = $row['available_date'];
                    $this->combinations[$row['id_product_attribute']]['date_formatted'] = Tools::displayDate($row['available_date']);
                } else {
                    $this->combinations[$row['id_product_attribute']]['available_date'] = $this->combinations[$row['id_product_attribute']]['date_formatted'] = '';
                }

                if (!isset($combination_images[$row['id_product_attribute']][0]['id_image'])) {
                    $this->combinations[$row['id_product_attribute']]['id_image'] = -1;
                } else {
                    $this->combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $combination_images[$row['id_product_attribute']][0]['id_image'];
                    if ($row['default_on']) {
                        foreach ($this->context->smarty->tpl_vars['product']->value['images'] as $image) {
                            if ($image['cover'] == 1) {
                                $current_cover = $image;
                            }
                        }
                        if (!isset($current_cover)) {
                            $current_cover = array_values($this->context->smarty->tpl_vars['product']->value['images'])[0];
                        }

                        if (is_array($combination_images[$row['id_product_attribute']])) {
                            foreach ($combination_images[$row['id_product_attribute']] as $tmp) {
                                if ($tmp['id_image'] == $current_cover['id_image']) {
                                    $this->combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $tmp['id_image'];

                                    break;
                                }
                            }
                        }

                        if ($id_image > 0) {
                            if (isset($this->context->smarty->tpl_vars['images']->value)) {
                                $product_images = $this->context->smarty->tpl_vars['images']->value;
                            }
                            if (isset($product_images) && is_array($product_images) && isset($product_images[$id_image])) {
                                $product_images[$id_image]['cover'] = 1;
                                $this->context->smarty->assign('mainImage', $product_images[$id_image]);
                                $this->context->smarty->assign('images', $product_images);
                            }

                            $cover = $current_cover;

                            if (isset($cover) && is_array($cover) && isset($product_images) && is_array($product_images)) {
                                $product_images[$cover['id_image']]['cover'] = 0;
                                if (isset($product_images[$id_image])) {
                                    $cover = $product_images[$id_image];
                                }
                                $cover['id_image'] = (Configuration::get('PS_LEGACY_IMAGES') ? ($this->product->id . '-' . $id_image) : (int) $id_image);
                                $cover['id_image_only'] = (int) $id_image;
                                $this->context->smarty->assign('cover', $cover);
                            }
                        }
                    }
                }
            //assign reference to each attribute
            $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']]['reference'] = $row['reference'];
            }

            // wash attributes list depending on available attributes depending on selected preceding attributes
            $current_selected_attributes = [];
            $count = 0;
            foreach ($groups as &$group) {
                ++$count;
                if ($count > 1) {
                    //find attributes of current group, having a possible combination with current selected
                    $id_product_attributes = [0];
                    $query = 'SELECT pac.`id_product_attribute`
                        FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac
                        INNER JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.id_product_attribute = pac.id_product_attribute
                        WHERE id_product = ' . $this->product->id . ' AND id_attribute IN (' . implode(',', array_map('intval', $current_selected_attributes)) . ')
                        GROUP BY id_product_attribute
                        HAVING COUNT(id_product) = ' . count($current_selected_attributes);
                    if ($results = Db::getInstance()->executeS($query)) {
                        foreach ($results as $row) {
                            $id_product_attributes[] = $row['id_product_attribute'];
                        }
                    }
                    $id_attributes = Db::getInstance()->executeS('SELECT pac2.`id_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac2' .
                        ((!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && 0 == Configuration::get('PS_DISP_UNAVAILABLE_ATTR')) ?
                        ' INNER JOIN `' . _DB_PREFIX_ . 'stock_available` pa ON pa.id_product_attribute = pac2.id_product_attribute
                        WHERE pa.quantity > 0 AND ' :
                        ' WHERE ') .
                        'pac2.`id_product_attribute` IN (' . implode(',', array_map('intval', $id_product_attributes)) . ')
                        AND pac2.id_attribute NOT IN (' . implode(',', array_map('intval', $current_selected_attributes)) . ')');
                    foreach ($id_attributes as $k => $row) {
                        $id_attributes[$k] = (int) $row['id_attribute'];
                    }
                    foreach ($group['attributes'] as $key => $attribute) {
                        if (!in_array((int) $key, $id_attributes)) {
                            unset(
                                $group['attributes'][$key],
                                $group['attributes_quantity'][$key]
                            );
                        }
                    }
                }
                //find selected attribute or first of group
                $index = 0;
                $current_selected_attribute = 0;
                foreach ($group['attributes'] as $key => $attribute) {
                    if ($index === 0) {
                        $current_selected_attribute = $key;
                    }
                    if ($attribute['selected']) {
                        $current_selected_attribute = $key;

                        break;
                    }
                }
                if ($current_selected_attribute > 0) {
                    $current_selected_attributes[] = $current_selected_attribute;
                }
            }

            // wash attributes list (if some attributes are unavailables and if allowed to wash it)
            if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {
                foreach ($groups as &$group) {
                    foreach ($group['attributes_quantity'] as $key => $quantity) {
                        if ($quantity <= 0) {
                            unset($group['attributes'][$key]);
                        }
                    }
                }

                foreach ($colors as $key => $color) {
                    if ($color['attributes_quantity'] <= 0) {
                        unset($colors[$key]);
                    }
                }
            }
            foreach ($this->combinations as $id_product_attribute => $comb) {
                $attribute_list = '';
                foreach ($comb['attributes'] as $id_attribute) {
                    $attribute_list .= '\'' . (int) $id_attribute . '\',';
                }
                $attribute_list = rtrim($attribute_list, ',');
                $this->combinations[$id_product_attribute]['list'] = $attribute_list;
            }
            unset($group);

            $this->context->smarty->assign([
                'groups' => $groups,
                'colors' => (count($colors)) ? $colors : false,
                'combinations' => $this->combinations,
                'combinationImages' => $combination_images,
            ]);
        } else {
            $this->context->smarty->assign([
                'groups' => [],
                'colors' => false,
                'combinations' => [],
                'combinationImages' => [],
            ]);
        }
    }

}

?>

What Im doing wrong?

Try to delete var/cache files.
 

Link to comment
Share on other sites

Hello, we've a new doubt related to this

Now that we are displaying the reference, is there a way to order the combinations by the reference?

They are displayed right now by the order of the attributes panel as default by prestashop, but having +4000 combinations in one attribute, it would be hard to order them manually

Link to comment
Share on other sites

Can you share some sample references so we can understand which way you want to order them? Also i would suggest to update attribute positions inside database than ordering it eachg time you render page.

First you should order them using reference, then update database positions with new order.

Link to comment
Share on other sites

On 1/20/2024 at 12:45 AM, WisQQ said:

Can you share some sample references so we can understand which way you want to order them? Also i would suggest to update attribute positions inside database than ordering it eachg time you render page.

First you should order them using reference, then update database positions with new order.

Our references go by numbers all of them

So product 1 has this references: 040001, 040002, 040003

But reference 040003 is newer, and when we imported it, it shows the first. So rn the order is 040003, 040001, 040002. We want to order them by the reference.

We can update them by the reference but, there are a lot of attributes (like +4000), is there a way to order them with a sql query?

Link to comment
Share on other sites

2 godziny temu, tecniconivelz napisał:

Our references go by numbers all of them

So product 1 has this references: 040001, 040002, 040003

But reference 040003 is newer, and when we imported it, it shows the first. So rn the order is 040003, 040001, 040002. We want to order them by the reference.

We can update them by the reference but, there are a lot of attributes (like +4000), is there a way to order them with a sql query?

Here is function that will sort numeric references.

function cmp( $a, $b ) { 
	if(  $a['reference'] ==  $b['reference'] ){
		return 0 ; 
	} 
	return ($a['reference'] < $b['reference']) ? 1 : -1;
}
usort($attributes_groups,'cmp');  
$attributes_groups = array_reverse($attributes_groups);


You have to place it before 

foreach ($attributes_groups as $k => $row) {

This will only work if your references are exacly as u sent.
There might be an issue if you try to order attributes by product references and set their position inside database, because attributes can be assigned to many different products which might have different references. If you are going to use those same attributes in different product, their order will set exacly the same as on product the sorting was done. 

 

Edited by WisQQ (see edit history)
  • Thanks 1
Link to comment
Share on other sites

43 minutes ago, WisQQ said:

Here is function that will sort numeric references.

function cmp( $a, $b ) { 
	if(  $a['reference'] ==  $b['reference'] ){
		return 0 ; 
	} 
	return ($a['reference'] < $b['reference']) ? 1 : -1;
}
usort($attributes_groups,'cmp');  
$attributes_groups = array_reverse($attributes_groups);


You have to place it before 

foreach ($attributes_groups as $k => $row) {

This will only work if your references are exacly as u sent.
There might be an issue if you try to order attributes by product references and set their position inside database, because attributes can be assigned to many different products which might have different references. If you are going to use those same attributes in different product, their order will set exacly the same as on product the sorting was done. 

 

You are amazing, that was exactly what we needed, it works perfectly

Thanks!!

Link to comment
Share on other sites

  • 4 months later...
Posted (edited)

Hi.

I have a similar problema. On product page I want to show the reference and the supplier reference, I have achieved this

{if isset($product.reference_to_display)}
                <div class="product-reference">
                    <label class="label">{l s='Reference' d='Shop.Theme.Catalog'} </label>
                    <span itemprop="sku">{$product.reference_to_display}</span>
                </div>
 {/if}
 {if isset($product.supplier_reference) && $product.supplier_reference != ''}    
                <div class="product-supplier-reference">
                    <label class="label">{l s='Referencia del fabricante' d='Shop.Theme.Catalog'} </label>
                    <span itemprop="sku">{$product.supplier_reference}</span>
                </div>
 {/if}

but when a product has combinations and you change to another combination, the page refreshes, but it continues to show the references of the product, not the combination

I have tried with the code that WissQQ says by overriding the ProductController.php, but in product.tpl when I do a var_dump of the $group variable it returns null, so I don't know what I'm doing wrong, nor if exactly this code will change me references when changing to another combination.

Can anybody help me?

 

Thanks

 

Edit: I'm using prestashop 8.1.3

Edited by María_Amieva
Forgot ps version (see edit history)
Link to comment
Share on other sites

Posted (edited)
Dnia 29.05.2024 o 8:26 PM, María_Amieva napisał:

Hi.

I have a similar problema. On product page I want to show the reference and the supplier reference, I have achieved this

{if isset($product.reference_to_display)}
                <div class="product-reference">
                    <label class="label">{l s='Reference' d='Shop.Theme.Catalog'} </label>
                    <span itemprop="sku">{$product.reference_to_display}</span>
                </div>
 {/if}
 {if isset($product.supplier_reference) && $product.supplier_reference != ''}    
                <div class="product-supplier-reference">
                    <label class="label">{l s='Referencia del fabricante' d='Shop.Theme.Catalog'} </label>
                    <span itemprop="sku">{$product.supplier_reference}</span>
                </div>
 {/if}

but when a product has combinations and you change to another combination, the page refreshes, but it continues to show the references of the product, not the combination

I have tried with the code that WissQQ says by overriding the ProductController.php, but in product.tpl when I do a var_dump of the $group variable it returns null, so I don't know what I'm doing wrong, nor if exactly this code will change me references when changing to another combination.

Can anybody help me?

 

Thanks

 

Edit: I'm using prestashop 8.1.3

Problem is you are showing default attribute on page load. Once you change combination it will reload parts of template using Ajax request.
To do what you want, you will have to return new option with ajax response. You can either override AjaxRefresh action inside ProductController and add new template to be returned or do it using Javascript after new tempaltes are returned just call your own module Controler that will return this value.

Another way you could simply add your code to template that is returned with ajax response and it should include proper reference.

Edited by WisQQ (see edit history)
Link to comment
Share on other sites

Hi.

I found a module that does what I need but it is for PrestaShop 1.7.
I have tried to adapt it for 8 and I find the following js

window.addEventListener('load', function() {
    prestashop.on('updatedProduct',function(event) {
        console.log('eventvars',event)
        $.ajax({
            type: 'POST',
            url: ajaxRequestUrl,
            cache: false,
            data: {
                ajax: true,
                method: 'dicombrefajax',
                product_attribute_id: event.id_product_attribute,
                id_product: event.id_product,
            },
            success: function (result) {
                //console.log(result);
                //IF REFERENCE EXISTS
                var parsedResult = false;
                try {
                    parsedResult = JSON.parse(result);
                } catch (error) {
                    console.error(error);
                }

                if (parsedResult) {
                    //HIDE PRODUCT REFERENCE
                    var divsToHide = document.getElementsByClassName("product-reference"); //divsToHide is an array
                    for(var i = 0; i < divsToHide.length; i++){
                        divsToHide[i].style.visibility = "hidden"; // or
                        divsToHide[i].style.display = "none"; // depending on what you're doing
                    }

                    //CHANGE COMBINATION REFERENCE
                    document.getElementById("discr-combination-sku").innerHTML = parsedResult.reference;

                    //SHOW COMBINATION REFERENCE
                    var sectionToShow = document.getElementById("selected-combination-reference");
                    if (sectionToShow) {
                        sectionToShow.style.visibility = "visible"; 
                        sectionToShow.style.display = "block";
                    }
                }
            }
        });
    });
});

The problem is that in version 8 updatedProduct does not capture the id_product, can someone help me?

Link to comment
Share on other sites

3 godziny temu, María_Amieva napisał:

Hi.

I found a module that does what I need but it is for PrestaShop 1.7.
I have tried to adapt it for 8 and I find the following js

window.addEventListener('load', function() {
    prestashop.on('updatedProduct',function(event) {
        console.log('eventvars',event)
        $.ajax({
            type: 'POST',
            url: ajaxRequestUrl,
            cache: false,
            data: {
                ajax: true,
                method: 'dicombrefajax',
                product_attribute_id: event.id_product_attribute,
                id_product: event.id_product,
            },
            success: function (result) {
                //console.log(result);
                //IF REFERENCE EXISTS
                var parsedResult = false;
                try {
                    parsedResult = JSON.parse(result);
                } catch (error) {
                    console.error(error);
                }

                if (parsedResult) {
                    //HIDE PRODUCT REFERENCE
                    var divsToHide = document.getElementsByClassName("product-reference"); //divsToHide is an array
                    for(var i = 0; i < divsToHide.length; i++){
                        divsToHide[i].style.visibility = "hidden"; // or
                        divsToHide[i].style.display = "none"; // depending on what you're doing
                    }

                    //CHANGE COMBINATION REFERENCE
                    document.getElementById("discr-combination-sku").innerHTML = parsedResult.reference;

                    //SHOW COMBINATION REFERENCE
                    var sectionToShow = document.getElementById("selected-combination-reference");
                    if (sectionToShow) {
                        sectionToShow.style.visibility = "visible"; 
                        sectionToShow.style.display = "block";
                    }
                }
            }
        });
    });
});

The problem is that in version 8 updatedProduct does not capture the id_product, can someone help me?

Can you paste here example event data? I dont have fresh ps8 to check it.

Link to comment
Share on other sites

This is what console shows

Object { product_prices: '<div class="product-prices"><div class="product-price h5 " itemprop="offers" itemscope itemtype="https://schema.org/Offer"><link itemprop="availability" href="https://schema.org/BackOrder" /><meta itemprop="priceCurrency" content="EUR"><div class="current-price"><span class="price" itemprop="price" content="44.9">44,90 €</span></div><div class="tvproduct-tax-label">Tax Included</div></div><div class="tax-shipping-delivery-label"><span></span><div class="avm_custom_text_priceblock">\n        \n</div></div></div>', product_cover_thumbnails: `<div class="page-contents product-1" id="content"><div class="images-container"><div class="product-cover col-xl-10 col-sm-9"><div class="tvproduct-image-slider"><ul class="tvproduct-flags tvproduct-online-new-wrapper"><li class="product-flag new">Nouveau</li></ul><ul class="tvproduct-flags tvproduct-sale-pack-wrapper"></ul><img class="js-qv-product-cover" src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" height="800" width="800" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" loading="lazy"><div class="layer" data-toggle="modal" data-target="#product-modal"><i class='material-icons'>&#xe3c2;</i></div></div></div><div class="tvvertical-slider col-xl-2 col-sm-3"><div class="product-images"><div class="tvcmsVerticalSlider item"><picture><source srcset="https://www.dentalipremium.com/4428-medium_default/limas-protaper-gold-25-mm-6-unidades.jpg" media="(max-width: 768px)"><img src="https://www.dentalipremium.com/4428-side_product_default/limas-protaper-gold-25-mm-6-unidades.jpg" class="thumb js-thumb  selected " data-image-medium-src="https://www.dentalipremium.com/4428-medium_default/limas-protaper-gold-25-mm-6-unidades.jpg" data-image-large-src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" height="86" width="86" loading="lazy"></picture></div></div><div class="arrows js-arrowsxx"><i class="tvvertical-slider-next material-icons arrow-up js-arrow-up">&#xE316;</i><i class="tvvertical-slider-pre material-icons arrow-down js-arrow-down">&#xE313;</i></div></div></div></div>`, product_customization: `<div class="product-customization"><div class="card card-block"><p class="h4 card-title">Personnalisation</p><p>N'oubliez pas de sauvegarder votre personnalisation pour pouvoir l'ajouter au panier</p><form method="post" action="https://www.dentalipremium.com/limas-rotatorias/limas-protaper-gold-25-mm-6-unidades.html#/1272-protaper_next_gold-f3" enctype="multipart/form-data"><ul class="clearfix"></ul><div class="clearfix"><button class="tvall-inner-btn float-xs-right" type="submit" name="submitCustomizedData"><span>Enregistrer la personnalisation</span></button></div></form></div></div>`, product_details: '<div class="tab-pane fade"id="product-details"data-product="{&quot;id_shop_default&quot;:1,&quot;id_manufacturer&quot;:34,&quot;id_supplier&quot;:0,&quot;reference&quot;:&quot;MA1330&quot;,&quot;is_virtual&quot;:&quot;0&quot;,&quot;delivery_in_stock&quot;:&quot;&quot;,&quot;delivery_out_stock&quot;:&quot;&quot;,&quot;id_category_default&quot;:267,&quot;on_sale&quot;:&quot;0&quot;,&quot;online_only&quot;:&quot;0&quot;,&quot;ecotax&quot;:0,&quot;minimal_quantity&quot;:1,&quot;low_stock_threshold&quot;:0,&quot;low_stock_alert&quot;:&quot;0&quot;,&quot;price&quot;:&quot;44,90\\u00a0\\u20ac&quot;,&quot;unity&quot;:&quot;&quot;,&quot;unit_price&quot;:&quot;0,00\\u00a0\\u20ac&quot;,&quot;unit_price_ratio&quot;:0,&quot;additional_shipping_cost&quot;:&quot;0.000000&quot;,&quot;customizable&quot;:0,&quot;text_fields&quot;:0,&quot;uploadable_files&quot;:0,&quot;active&quot;:&quot;1&quot;,&quot;redirect_type&quot;:&quot;default&quot;,&quot;id_type_redirected&quot;:0,&quot;available_for_order&quot;:&qu…', product_variants: '<div class="product-variants"><div class="clearfix product-variants-item"><span class="control-label">Medida lima : </span><select class="form-control form-control-select" id="group_23" data-product-attribute="23" name="group[23]"><option value="1270" title="F1">F1</option><option value="1271" title="F2">F2</option><option value="1272" title="F3" selected="selected">F3</option><option value="1282" title="S1">S1</option><option value="1283" title="S2">S2</option><option value="1284" title="F4">F4</option><option value="1285" title="F5">F5</option><option value="1286" title="SURTIDO">SURTIDO</option></select></div></div>', product_discounts: "", product_add_to_cart: `<div class="product-add-to-cart"><div class="product-quantity"><span class="control-label">Quantity : </span><div class="qty"><input type="text" name="qty" id="quantity_wanted" value="1" class="input-group" min="1" aria-label="Quantité"></div></div><div class='tvwishlist-compare-wrapper-page add tv-product-page-add-to-cart-wrapper'><div class="tvcart-btn-model"><button class="tvall-inner-btn add-to-cart " data-button-action="add-to-cart" type="submit" > <i class="material-icons shopping-cart">&#xE547;</i><span>Ajouter au panier</span></button></div><div class="tvproduct-wishlist-compare"></div><div class="tvproduct-stock-social"><div class="tv-product-page clearfix"><div class="tv-indicator tv-pie tv-colors"><div class="tv-outer" data-toggle="tvtooltip" data-placement="top" data-html="true" title="<div class='text-center'>État des stocks\t: <b>En rupture de stock\t</b></div>" ><div class="tv-inner tv-lvl-0"></div></div></div></div><div class="product-additional-info"></div></div></div></div>`, product_additional_info: '<div class="product-additional-info"></div>', product_images_modal: '<div class="modal fade js-product-images-modal" id="product-modal"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="tvmodel-close close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div><div class="modal-body"><figure><img class="js-modal-product-cover product-cover-modal" width="800" src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" loading="lazy"><figcaption class="image-caption"><div id="product-description-short" itemprop="description"></div></figcaption></figure><aside id="thumbnails" class="thumbnails js-thumbnails text-sm-center"><div class="js-modal-mask mask  nomargin "><ul class="product-images js-modal-product-images"><li class="thumb-container"><img data-image-large-src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" class="thumb js-modal-thumb" src="https://www.dentalipremium.com/4428-add_cart_def/limas-protaper-gold-25-mm-6-unidades.jpg"  alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" width="150" itemprop="image" loading="lazy"></li></ul></div><div><i></i></div></aside></div></div><!-- /.modal-content --></div><!-- /.modal-dialog --></div><!-- /.modal -->', product_url: "https://www.dentalipremium.com/limas-rotatorias/limas-protaper-gold-25-mm-6-unidades.html#/1272-protaper_next_gold-f3", … }
id_customization: 0
id_product_attribute: 9576
is_quick_view: false
product_add_to_cart: `<div class="product-add-to-cart"><div class="product-quantity"><span class="control-label">Quantity : </span><div class="qty"><input type="text" name="qty" id="quantity_wanted" value="1" class="input-group" min="1" aria-label="Quantité"></div></div><div class='tvwishlist-compare-wrapper-page add tv-product-page-add-to-cart-wrapper'><div class="tvcart-btn-model"><button class="tvall-inner-btn add-to-cart " data-button-action="add-to-cart" type="submit" > <i class="material-icons shopping-cart">&#xE547;</i><span>Ajouter au panier</span></button></div><div class="tvproduct-wishlist-compare"></div><div class="tvproduct-stock-social"><div class="tv-product-page clearfix"><div class="tv-indicator tv-pie tv-colors"><div class="tv-outer" data-toggle="tvtooltip" data-placement="top" data-html="true" title="<div class='text-center'>État des stocks\t: <b>En rupture de stock\t</b></div>" ><div class="tv-inner tv-lvl-0"></div></div></div></div><div class="product-additional-info"></div></div></div></div>`
product_additional_info: '<div class="product-additional-info"></div>'
product_cover_thumbnails: `<div class="page-contents product-1" id="content"><div class="images-container"><div class="product-cover col-xl-10 col-sm-9"><div class="tvproduct-image-slider"><ul class="tvproduct-flags tvproduct-online-new-wrapper"><li class="product-flag new">Nouveau</li></ul><ul class="tvproduct-flags tvproduct-sale-pack-wrapper"></ul><img class="js-qv-product-cover" src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" height="800" width="800" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" loading="lazy"><div class="layer" data-toggle="modal" data-target="#product-modal"><i class='material-icons'>&#xe3c2;</i></div></div></div><div class="tvvertical-slider col-xl-2 col-sm-3"><div class="product-images"><div class="tvcmsVerticalSlider item"><picture><source srcset="https://www.dentalipremium.com/4428-medium_default/limas-protaper-gold-25-mm-6-unidades.jpg" media="(max-width: 768px)"><img src="https://www.dentalipremium.com/4428-side_product_default/limas-protaper-gold-25-mm-6-unidades.jpg" class="thumb js-thumb  selected " data-image-medium-src="https://www.dentalipremium.com/4428-medium_default/limas-protaper-gold-25-mm-6-unidades.jpg" data-image-large-src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" height="86" width="86" loading="lazy"></picture></div></div><div class="arrows js-arrowsxx"><i class="tvvertical-slider-next material-icons arrow-up js-arrow-up">&#xE316;</i><i class="tvvertical-slider-pre material-icons arrow-down js-arrow-down">&#xE313;</i></div></div></div></div>`
product_customization: `<div class="product-customization"><div class="card card-block"><p class="h4 card-title">Personnalisation</p><p>N'oubliez pas de sauvegarder votre personnalisation pour pouvoir l'ajouter au panier</p><form method="post" action="https://www.dentalipremium.com/limas-rotatorias/limas-protaper-gold-25-mm-6-unidades.html#/1272-protaper_next_gold-f3" enctype="multipart/form-data"><ul class="clearfix"></ul><div class="clearfix"><button class="tvall-inner-btn float-xs-right" type="submit" name="submitCustomizedData"><span>Enregistrer la personnalisation</span></button></div></form></div></div>`
product_details: '<div class="tab-pane fade"id="product-details"data-product="{&quot;id_shop_default&quot;:1,&quot;id_manufacturer&quot;:34,&quot;id_supplier&quot;:0,&quot;reference&quot;:&quot;MA1330&quot;,&quot;is_virtual&quot;:&quot;0&quot;,&quot;delivery_in_stock&quot;:&quot;&quot;,&quot;delivery_out_stock&quot;:&quot;&quot;,&quot;id_category_default&quot;:267,&quot;on_sale&quot;:&quot;0&quot;,&quot;online_only&quot;:&quot;0&quot;,&quot;ecotax&quot;:0,&quot;minimal_quantity&quot;:1,&quot;low_stock_threshold&quot;:0,&quot;low_stock_alert&quot;:&quot;0&quot;,&quot;price&quot;:&quot;44,90\\u00a0\\u20ac&quot;,&quot;unity&quot;:&quot;&quot;,&quot;unit_price&quot;:&quot;0,00\\u00a0\\u20ac&quot;,&quot;unit_price_ratio&quot;:0,&quot;additional_shipping_cost&quot;:&quot;0.000000&quot;,&quot;customizable&quot;:0,&quot;text_fields&quot;:0,&quot;uploadable_files&quot;:0,&quot;active&quot;:&quot;1&quot;,&quot;redirect_type&quot;:&quot;default&quot;,&quot;id_type_redirected&quot;:0,&quot;available_for_order&quot;:&qu…'
product_discounts: ""
product_has_combinations: true
product_images_modal: '<div class="modal fade js-product-images-modal" id="product-modal"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="tvmodel-close close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div><div class="modal-body"><figure><img class="js-modal-product-cover product-cover-modal" width="800" src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" loading="lazy"><figcaption class="image-caption"><div id="product-description-short" itemprop="description"></div></figcaption></figure><aside id="thumbnails" class="thumbnails js-thumbnails text-sm-center"><div class="js-modal-mask mask  nomargin "><ul class="product-images js-modal-product-images"><li class="thumb-container"><img data-image-large-src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" class="thumb js-modal-thumb" src="https://www.dentalipremium.com/4428-add_cart_def/limas-protaper-gold-25-mm-6-unidades.jpg"  alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" width="150" itemprop="image" loading="lazy"></li></ul></div><div><i></i></div></aside></div></div><!-- /.modal-content --></div><!-- /.modal-dialog --></div><!-- /.modal -->'
product_minimal_quantity: 1
product_prices: '<div class="product-prices"><div class="product-price h5 " itemprop="offers" itemscope itemtype="https://schema.org/Offer"><link itemprop="availability" href="https://schema.org/BackOrder" /><meta itemprop="priceCurrency" content="EUR"><div class="current-price"><span class="price" itemprop="price" content="44.9">44,90 €</span></div><div class="tvproduct-tax-label">Tax Included</div></div><div class="tax-shipping-delivery-label"><span></span><div class="avm_custom_text_priceblock">\n        \n</div></div></div>'
product_title: "LIMAS PROTAPER GOLD 25 mm 6 unidades"
product_url: "https://www.dentalipremium.com/limas-rotatorias/limas-protaper-gold-25-mm-6-unidades.html#/1272-protaper_next_gold-f3"
product_variants: '<div class="product-variants"><div class="clearfix product-variants-item"><span class="control-label">Medida lima : </span><select class="form-control form-control-select" id="group_23" data-product-attribute="23" name="group[23]"><option value="1270" title="F1">F1</option><option value="1271" title="F2">F2</option><option value="1272" title="F3" selected="selected">F3</option><option value="1282" title="S1">S1</option><option value="1283" title="S2">S2</option><option value="1284" title="F4">F4</option><option value="1285" title="F5">F5</option><option value="1286" title="SURTIDO">SURTIDO</option></select></div></div>'

I'm going crazy trying to get id_product from product_details

Link to comment
Share on other sites

4 godziny temu, María_Amieva napisał:

This is what console shows

Object { product_prices: '<div class="product-prices"><div class="product-price h5 " itemprop="offers" itemscope itemtype="https://schema.org/Offer"><link itemprop="availability" href="https://schema.org/BackOrder" /><meta itemprop="priceCurrency" content="EUR"><div class="current-price"><span class="price" itemprop="price" content="44.9">44,90 €</span></div><div class="tvproduct-tax-label">Tax Included</div></div><div class="tax-shipping-delivery-label"><span></span><div class="avm_custom_text_priceblock">\n        \n</div></div></div>', product_cover_thumbnails: `<div class="page-contents product-1" id="content"><div class="images-container"><div class="product-cover col-xl-10 col-sm-9"><div class="tvproduct-image-slider"><ul class="tvproduct-flags tvproduct-online-new-wrapper"><li class="product-flag new">Nouveau</li></ul><ul class="tvproduct-flags tvproduct-sale-pack-wrapper"></ul><img class="js-qv-product-cover" src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" height="800" width="800" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" loading="lazy"><div class="layer" data-toggle="modal" data-target="#product-modal"><i class='material-icons'>&#xe3c2;</i></div></div></div><div class="tvvertical-slider col-xl-2 col-sm-3"><div class="product-images"><div class="tvcmsVerticalSlider item"><picture><source srcset="https://www.dentalipremium.com/4428-medium_default/limas-protaper-gold-25-mm-6-unidades.jpg" media="(max-width: 768px)"><img src="https://www.dentalipremium.com/4428-side_product_default/limas-protaper-gold-25-mm-6-unidades.jpg" class="thumb js-thumb  selected " data-image-medium-src="https://www.dentalipremium.com/4428-medium_default/limas-protaper-gold-25-mm-6-unidades.jpg" data-image-large-src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" height="86" width="86" loading="lazy"></picture></div></div><div class="arrows js-arrowsxx"><i class="tvvertical-slider-next material-icons arrow-up js-arrow-up">&#xE316;</i><i class="tvvertical-slider-pre material-icons arrow-down js-arrow-down">&#xE313;</i></div></div></div></div>`, product_customization: `<div class="product-customization"><div class="card card-block"><p class="h4 card-title">Personnalisation</p><p>N'oubliez pas de sauvegarder votre personnalisation pour pouvoir l'ajouter au panier</p><form method="post" action="https://www.dentalipremium.com/limas-rotatorias/limas-protaper-gold-25-mm-6-unidades.html#/1272-protaper_next_gold-f3" enctype="multipart/form-data"><ul class="clearfix"></ul><div class="clearfix"><button class="tvall-inner-btn float-xs-right" type="submit" name="submitCustomizedData"><span>Enregistrer la personnalisation</span></button></div></form></div></div>`, product_details: '<div class="tab-pane fade"id="product-details"data-product="{&quot;id_shop_default&quot;:1,&quot;id_manufacturer&quot;:34,&quot;id_supplier&quot;:0,&quot;reference&quot;:&quot;MA1330&quot;,&quot;is_virtual&quot;:&quot;0&quot;,&quot;delivery_in_stock&quot;:&quot;&quot;,&quot;delivery_out_stock&quot;:&quot;&quot;,&quot;id_category_default&quot;:267,&quot;on_sale&quot;:&quot;0&quot;,&quot;online_only&quot;:&quot;0&quot;,&quot;ecotax&quot;:0,&quot;minimal_quantity&quot;:1,&quot;low_stock_threshold&quot;:0,&quot;low_stock_alert&quot;:&quot;0&quot;,&quot;price&quot;:&quot;44,90\\u00a0\\u20ac&quot;,&quot;unity&quot;:&quot;&quot;,&quot;unit_price&quot;:&quot;0,00\\u00a0\\u20ac&quot;,&quot;unit_price_ratio&quot;:0,&quot;additional_shipping_cost&quot;:&quot;0.000000&quot;,&quot;customizable&quot;:0,&quot;text_fields&quot;:0,&quot;uploadable_files&quot;:0,&quot;active&quot;:&quot;1&quot;,&quot;redirect_type&quot;:&quot;default&quot;,&quot;id_type_redirected&quot;:0,&quot;available_for_order&quot;:&qu…', product_variants: '<div class="product-variants"><div class="clearfix product-variants-item"><span class="control-label">Medida lima : </span><select class="form-control form-control-select" id="group_23" data-product-attribute="23" name="group[23]"><option value="1270" title="F1">F1</option><option value="1271" title="F2">F2</option><option value="1272" title="F3" selected="selected">F3</option><option value="1282" title="S1">S1</option><option value="1283" title="S2">S2</option><option value="1284" title="F4">F4</option><option value="1285" title="F5">F5</option><option value="1286" title="SURTIDO">SURTIDO</option></select></div></div>', product_discounts: "", product_add_to_cart: `<div class="product-add-to-cart"><div class="product-quantity"><span class="control-label">Quantity : </span><div class="qty"><input type="text" name="qty" id="quantity_wanted" value="1" class="input-group" min="1" aria-label="Quantité"></div></div><div class='tvwishlist-compare-wrapper-page add tv-product-page-add-to-cart-wrapper'><div class="tvcart-btn-model"><button class="tvall-inner-btn add-to-cart " data-button-action="add-to-cart" type="submit" > <i class="material-icons shopping-cart">&#xE547;</i><span>Ajouter au panier</span></button></div><div class="tvproduct-wishlist-compare"></div><div class="tvproduct-stock-social"><div class="tv-product-page clearfix"><div class="tv-indicator tv-pie tv-colors"><div class="tv-outer" data-toggle="tvtooltip" data-placement="top" data-html="true" title="<div class='text-center'>État des stocks\t: <b>En rupture de stock\t</b></div>" ><div class="tv-inner tv-lvl-0"></div></div></div></div><div class="product-additional-info"></div></div></div></div>`, product_additional_info: '<div class="product-additional-info"></div>', product_images_modal: '<div class="modal fade js-product-images-modal" id="product-modal"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="tvmodel-close close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div><div class="modal-body"><figure><img class="js-modal-product-cover product-cover-modal" width="800" src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" loading="lazy"><figcaption class="image-caption"><div id="product-description-short" itemprop="description"></div></figcaption></figure><aside id="thumbnails" class="thumbnails js-thumbnails text-sm-center"><div class="js-modal-mask mask  nomargin "><ul class="product-images js-modal-product-images"><li class="thumb-container"><img data-image-large-src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" class="thumb js-modal-thumb" src="https://www.dentalipremium.com/4428-add_cart_def/limas-protaper-gold-25-mm-6-unidades.jpg"  alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" width="150" itemprop="image" loading="lazy"></li></ul></div><div><i></i></div></aside></div></div><!-- /.modal-content --></div><!-- /.modal-dialog --></div><!-- /.modal -->', product_url: "https://www.dentalipremium.com/limas-rotatorias/limas-protaper-gold-25-mm-6-unidades.html#/1272-protaper_next_gold-f3", … }
id_customization: 0
id_product_attribute: 9576
is_quick_view: false
product_add_to_cart: `<div class="product-add-to-cart"><div class="product-quantity"><span class="control-label">Quantity : </span><div class="qty"><input type="text" name="qty" id="quantity_wanted" value="1" class="input-group" min="1" aria-label="Quantité"></div></div><div class='tvwishlist-compare-wrapper-page add tv-product-page-add-to-cart-wrapper'><div class="tvcart-btn-model"><button class="tvall-inner-btn add-to-cart " data-button-action="add-to-cart" type="submit" > <i class="material-icons shopping-cart">&#xE547;</i><span>Ajouter au panier</span></button></div><div class="tvproduct-wishlist-compare"></div><div class="tvproduct-stock-social"><div class="tv-product-page clearfix"><div class="tv-indicator tv-pie tv-colors"><div class="tv-outer" data-toggle="tvtooltip" data-placement="top" data-html="true" title="<div class='text-center'>État des stocks\t: <b>En rupture de stock\t</b></div>" ><div class="tv-inner tv-lvl-0"></div></div></div></div><div class="product-additional-info"></div></div></div></div>`
product_additional_info: '<div class="product-additional-info"></div>'
product_cover_thumbnails: `<div class="page-contents product-1" id="content"><div class="images-container"><div class="product-cover col-xl-10 col-sm-9"><div class="tvproduct-image-slider"><ul class="tvproduct-flags tvproduct-online-new-wrapper"><li class="product-flag new">Nouveau</li></ul><ul class="tvproduct-flags tvproduct-sale-pack-wrapper"></ul><img class="js-qv-product-cover" src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" height="800" width="800" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" loading="lazy"><div class="layer" data-toggle="modal" data-target="#product-modal"><i class='material-icons'>&#xe3c2;</i></div></div></div><div class="tvvertical-slider col-xl-2 col-sm-3"><div class="product-images"><div class="tvcmsVerticalSlider item"><picture><source srcset="https://www.dentalipremium.com/4428-medium_default/limas-protaper-gold-25-mm-6-unidades.jpg" media="(max-width: 768px)"><img src="https://www.dentalipremium.com/4428-side_product_default/limas-protaper-gold-25-mm-6-unidades.jpg" class="thumb js-thumb  selected " data-image-medium-src="https://www.dentalipremium.com/4428-medium_default/limas-protaper-gold-25-mm-6-unidades.jpg" data-image-large-src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" height="86" width="86" loading="lazy"></picture></div></div><div class="arrows js-arrowsxx"><i class="tvvertical-slider-next material-icons arrow-up js-arrow-up">&#xE316;</i><i class="tvvertical-slider-pre material-icons arrow-down js-arrow-down">&#xE313;</i></div></div></div></div>`
product_customization: `<div class="product-customization"><div class="card card-block"><p class="h4 card-title">Personnalisation</p><p>N'oubliez pas de sauvegarder votre personnalisation pour pouvoir l'ajouter au panier</p><form method="post" action="https://www.dentalipremium.com/limas-rotatorias/limas-protaper-gold-25-mm-6-unidades.html#/1272-protaper_next_gold-f3" enctype="multipart/form-data"><ul class="clearfix"></ul><div class="clearfix"><button class="tvall-inner-btn float-xs-right" type="submit" name="submitCustomizedData"><span>Enregistrer la personnalisation</span></button></div></form></div></div>`
product_details: '<div class="tab-pane fade"id="product-details"data-product="{&quot;id_shop_default&quot;:1,&quot;id_manufacturer&quot;:34,&quot;id_supplier&quot;:0,&quot;reference&quot;:&quot;MA1330&quot;,&quot;is_virtual&quot;:&quot;0&quot;,&quot;delivery_in_stock&quot;:&quot;&quot;,&quot;delivery_out_stock&quot;:&quot;&quot;,&quot;id_category_default&quot;:267,&quot;on_sale&quot;:&quot;0&quot;,&quot;online_only&quot;:&quot;0&quot;,&quot;ecotax&quot;:0,&quot;minimal_quantity&quot;:1,&quot;low_stock_threshold&quot;:0,&quot;low_stock_alert&quot;:&quot;0&quot;,&quot;price&quot;:&quot;44,90\\u00a0\\u20ac&quot;,&quot;unity&quot;:&quot;&quot;,&quot;unit_price&quot;:&quot;0,00\\u00a0\\u20ac&quot;,&quot;unit_price_ratio&quot;:0,&quot;additional_shipping_cost&quot;:&quot;0.000000&quot;,&quot;customizable&quot;:0,&quot;text_fields&quot;:0,&quot;uploadable_files&quot;:0,&quot;active&quot;:&quot;1&quot;,&quot;redirect_type&quot;:&quot;default&quot;,&quot;id_type_redirected&quot;:0,&quot;available_for_order&quot;:&qu…'
product_discounts: ""
product_has_combinations: true
product_images_modal: '<div class="modal fade js-product-images-modal" id="product-modal"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="tvmodel-close close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div><div class="modal-body"><figure><img class="js-modal-product-cover product-cover-modal" width="800" src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" itemprop="image" loading="lazy"><figcaption class="image-caption"><div id="product-description-short" itemprop="description"></div></figcaption></figure><aside id="thumbnails" class="thumbnails js-thumbnails text-sm-center"><div class="js-modal-mask mask  nomargin "><ul class="product-images js-modal-product-images"><li class="thumb-container"><img data-image-large-src="https://www.dentalipremium.com/4428-large_default/limas-protaper-gold-25-mm-6-unidades.jpg" class="thumb js-modal-thumb" src="https://www.dentalipremium.com/4428-add_cart_def/limas-protaper-gold-25-mm-6-unidades.jpg"  alt="LIMAS PROTAPER GOLD 25 mm 6 unidades" title="LIMAS PROTAPER GOLD 25 mm 6 unidades" width="150" itemprop="image" loading="lazy"></li></ul></div><div><i></i></div></aside></div></div><!-- /.modal-content --></div><!-- /.modal-dialog --></div><!-- /.modal -->'
product_minimal_quantity: 1
product_prices: '<div class="product-prices"><div class="product-price h5 " itemprop="offers" itemscope itemtype="https://schema.org/Offer"><link itemprop="availability" href="https://schema.org/BackOrder" /><meta itemprop="priceCurrency" content="EUR"><div class="current-price"><span class="price" itemprop="price" content="44.9">44,90 €</span></div><div class="tvproduct-tax-label">Tax Included</div></div><div class="tax-shipping-delivery-label"><span></span><div class="avm_custom_text_priceblock">\n        \n</div></div></div>'
product_title: "LIMAS PROTAPER GOLD 25 mm 6 unidades"
product_url: "https://www.dentalipremium.com/limas-rotatorias/limas-protaper-gold-25-mm-6-unidades.html#/1272-protaper_next_gold-f3"
product_variants: '<div class="product-variants"><div class="clearfix product-variants-item"><span class="control-label">Medida lima : </span><select class="form-control form-control-select" id="group_23" data-product-attribute="23" name="group[23]"><option value="1270" title="F1">F1</option><option value="1271" title="F2">F2</option><option value="1272" title="F3" selected="selected">F3</option><option value="1282" title="S1">S1</option><option value="1283" title="S2">S2</option><option value="1284" title="F4">F4</option><option value="1285" title="F5">F5</option><option value="1286" title="SURTIDO">SURTIDO</option></select></div></div>'

I'm going crazy trying to get id_product from product_details

This is exacly the same reponse you get from ps 1.7
Try this to get product id from product-details:
 

$("div#product-details").data('product').id_product;

 

Link to comment
Share on other sites

Well, if it is the same response in ps 1.7 and 8, I don't understand why it doesn't work, when I do the console log with event.id_product it tells me undefined

$("div#product-details").data('product').id_product; returns Uncaught TypeError: "div#product-details".data is not a function

Link to comment
Share on other sites

6 minut temu, María_Amieva napisał:

Well, if it is the same response in ps 1.7 and 8, I don't understand why it doesn't work, when I do the console log with event.id_product it tells me undefined

$("div#product-details").data('product').id_product; returns Uncaught TypeError: "div#product-details".data is not a function

what template are you using?

Link to comment
Share on other sites

I have managed to advance one step only to get stuck in the next

Thanks to WisQQ I have obtained the id_product so the js would look like this

window.addEventListener('load', function() {
    prestashop.on('updatedProduct',function(event) {
        console.log(event);
        var id_product= $("div#product-details").data('product').id_product;
        $.ajax({
            type: 'POST',
            url: ajaxRequestUrl,
            cache: false,
            data: {
                ajax: true,
                method: 'dicombrefajax',
                product_attribute_id: event.id_product_attribute,
                id_product: id_product
            },
            success: function (result) {
                console.log(result);
                //IF REFERENCE EXISTS
                var parsedResult = false;
                try {
                    parsedResult = JSON.parse(result);
                } catch (error) {
                    console.error(error);
                }

                if (parsedResult) {
                    //HIDE PRODUCT REFERENCE
                    var divsToHide = document.getElementsByClassName("product-reference"); //divsToHide is an array
                    for(var i = 0; i < divsToHide.length; i++){
                        divsToHide[i].style.visibility = "hidden"; // or
                        divsToHide[i].style.display = "none"; // depending on what you're doing
                    }

                    //CHANGE COMBINATION REFERENCE
                    document.getElementById("discr-combination-sku").innerHTML = parsedResult.reference;

                    //SHOW COMBINATION REFERENCE
                    var sectionToShow = document.getElementById("selected-combination-reference");
                    if (sectionToShow) {
                        sectionToShow.style.visibility = "visible"; 
                        sectionToShow.style.display = "block";
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown){
                console.log(XMLHttpRequest);
                console.log(textStatus);
                console.log(errorThrown);
            }
            
        });  
    });
});

For some reason that I don't know, the ajax function gives error 500🤦‍♀️

Link to comment
Share on other sites

Dnia 3.06.2024 o 9:28 PM, María_Amieva napisał:

I tested function on demo and it properly returns product id
 

console.log($("div#product-details").data('product').id_product);

 

Link to comment
Share on other sites

Dnia 5.06.2024 o 2:07 PM, María_Amieva napisał:

I have managed to advance one step only to get stuck in the next

Thanks to WisQQ I have obtained the id_product so the js would look like this

window.addEventListener('load', function() {
    prestashop.on('updatedProduct',function(event) {
        console.log(event);
        var id_product= $("div#product-details").data('product').id_product;
        $.ajax({
            type: 'POST',
            url: ajaxRequestUrl,
            cache: false,
            data: {
                ajax: true,
                method: 'dicombrefajax',
                product_attribute_id: event.id_product_attribute,
                id_product: id_product
            },
            success: function (result) {
                console.log(result);
                //IF REFERENCE EXISTS
                var parsedResult = false;
                try {
                    parsedResult = JSON.parse(result);
                } catch (error) {
                    console.error(error);
                }

                if (parsedResult) {
                    //HIDE PRODUCT REFERENCE
                    var divsToHide = document.getElementsByClassName("product-reference"); //divsToHide is an array
                    for(var i = 0; i < divsToHide.length; i++){
                        divsToHide[i].style.visibility = "hidden"; // or
                        divsToHide[i].style.display = "none"; // depending on what you're doing
                    }

                    //CHANGE COMBINATION REFERENCE
                    document.getElementById("discr-combination-sku").innerHTML = parsedResult.reference;

                    //SHOW COMBINATION REFERENCE
                    var sectionToShow = document.getElementById("selected-combination-reference");
                    if (sectionToShow) {
                        sectionToShow.style.visibility = "visible"; 
                        sectionToShow.style.display = "block";
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown){
                console.log(XMLHttpRequest);
                console.log(textStatus);
                console.log(errorThrown);
            }
            
        });  
    });
});

For some reason that I don't know, the ajax function gives error 500🤦‍♀️

Turn on debug mode and it should return with proper error message.

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
×
×
  • Create New...