Jump to content

Usar una variable de la base de datos en un tpl ( o js )


nersolar

Recommended Posts

Buenas tardes a todos

 

He conseguido hacer un campo en la pestaña de combinaciones en el backoffice, y tambien he conseguido que cuando relleno ese campo se guarda correctamente en la tabla de ps_product_attribute

 

Así que genial! he conseguido hacer una nueva variable en la base de datos en la tabla que yo queria, pero ahora mi problema es ....

 

Como uso esa variable en product.tpl? o, mejor aún, como la uso en product.js para que cambie cuando cambiamos de combinacion??

 

alguien puede ayudarme?

Link to comment
Share on other sites

Tienes que incluirlo en la query de la classe Product.php, funcion

  getAttributesGroups

y tambien en el ProductController.php en la funcion

assignAttributesGroups

asi lo tendras en el array del product.tpl

$combinations

y podras añadirlo en el array del product.js

combinationsJS
Link to comment
Share on other sites

muchas gracias por tu respuesta pero no acabo de entender alguna cosilla o es que no lo hago bien.

 

 

en el archivo /classes/product.php

public $potencia;

public function getAttributesGroups($id_lang)
    {
        if (!Combination::isFeatureActive()) {
            return array();
        }
        $sql = 'SELECT ag.`id_attribute_group`, ag.`is_color_group`, agl.`name` AS group_name, agl.`public_name` AS public_group_name,
					a.`id_attribute`, al.`name` AS attribute_name, a.`color` AS attribute_color, product_attribute_shop.`id_product_attribute`,
					IFNULL(stock.quantity, 0) as quantity, product_attribute_shop.`price`, product_attribute_shop.`ecotax`, product_attribute_shop.`weight`,
					product_attribute_shop.`default_on`, pa.`reference`, pa.`potencia`, product_attribute_shop.`unit_price_impact`,
					product_attribute_shop.`minimal_quantity`, product_attribute_shop.`available_date`, ag.`group_type`
				FROM `'._DB_PREFIX_.'product_attribute` pa
				'.Shop::addSqlAssociation('product_attribute', 'pa').'
				'.Product::sqlStock('pa', 'pa').'
				LEFT JOIN `'._DB_PREFIX_.'product_attribute_combination` pac ON (pac.`id_product_attribute` = pa.`id_product_attribute`)
				LEFT JOIN `'._DB_PREFIX_.'attribute` a ON (a.`id_attribute` = pac.`id_attribute`)
				LEFT JOIN `'._DB_PREFIX_.'attribute_group` ag ON (ag.`id_attribute_group` = a.`id_attribute_group`)
				LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute`)
				LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group`)
				'.Shop::addSqlAssociation('attribute', 'a').'
				WHERE pa.`id_product` = '.(int)$this->id.'
					AND al.`id_lang` = '.(int)$id_lang.'
					AND agl.`id_lang` = '.(int)$id_lang.'
				GROUP BY id_attribute_group, id_product_attribute
				ORDER BY ag.`position` ASC, a.`position` ASC, agl.`name` ASC';
        return Db::getInstance()->executeS($sql);
    }

en el archivo ProductController.php

    protected function assignAttributesGroups()
    {
        $colors = array();
        $groups = array();

        // @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 = array();
            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']] = array(
                        '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']] = $row['attribute_name'];
                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'];

                $combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
                $combinations[$row['id_product_attribute']]['attributes'][] = (int)$row['id_attribute'];
				$combinations[$row['id_product_attribute']]['potencia'] = $row['potencia'];
                $combinations[$row['id_product_attribute']]['price'] = (float)Tools::convertPriceFull($row['price'], null, Context::getContext()->currency);

                // Call getPriceStatic in order to set $combination_specific_price
                if (!isset($combination_prices_set[(int)$row['id_product_attribute']])) {
                    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;
                    $combinations[$row['id_product_attribute']]['specific_price'] = $combination_specific_price;
                }
                $combinations[$row['id_product_attribute']]['ecotax'] = (float)$row['ecotax'];
                $combinations[$row['id_product_attribute']]['weight'] = (float)$row['weight'];
                $combinations[$row['id_product_attribute']]['quantity'] = (int)$row['quantity'];
                $combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
                $combinations[$row['id_product_attribute']]['unit_impact'] = Tools::convertPriceFull($row['unit_price_impact'], null, Context::getContext()->currency);
                $combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
                if ($row['available_date'] != '0000-00-00' && Validate::isDate($row['available_date'])) {
                    $combinations[$row['id_product_attribute']]['available_date'] = $row['available_date'];
                    $combinations[$row['id_product_attribute']]['date_formatted'] = Tools::displayDate($row['available_date']);
                } else {
                    $combinations[$row['id_product_attribute']]['available_date'] = $combinations[$row['id_product_attribute']]['date_formatted'] = '';
                }

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

                        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']) {
                                    $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);
                                }
                            }
                            if (isset($this->context->smarty->tpl_vars['cover']->value)) {
                                $cover = $this->context->smarty->tpl_vars['cover']->value;
                            }
                            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);
                            }
                        }
                    }
                }
            }

            // 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 ($combinations as $id_product_attribute => $comb) {
                $attribute_list = '';
                foreach ($comb['attributes'] as $id_attribute) {
                    $attribute_list .= '\''.(int)$id_attribute.'\',';
                }
                $attribute_list = rtrim($attribute_list, ',');
                $combinations[$id_product_attribute]['list'] = $attribute_list;
            }

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

luego en en product.tpl no se que llamar. no se si usar {$potencia} o usar {$combinations->potencia} o {product->potencia} no me funciona nada y no se que hago mal...

en el JS tampoco se llamar a $potencia para que salga en algun sitio.

 

Link to comment
Share on other sites

1. Incluirlo en la query de la funcion de la classe Product.php, en el select de la consulta como estan los demas valores del select

2. Añadirlo en el array combinations de la funcion del ProductController.php

3. En el product.tpl se incluye el array combinations para enviarlo al product.js y que estos valores aparezcan de manera dinamica dependiendo de lo que se seleccione

  • Like 1
Link to comment
Share on other sites

1. Incluirlo en la query de la funcion de la classe Product.php, en el select de la consulta como estan los demas valores del select

2. Añadirlo en el array combinations de la funcion del ProductController.php

3. En el product.tpl se incluye el array combinations para enviarlo al product.js y que estos valores aparezcan de manera dinamica dependiendo de lo que se seleccione

 

Qué va ... que soy muy torpe, no entiendo en que "query" ni en que "funcion" del archivo "product.php" tengo que poner la variable.

 

Tampoco se en que "array combinations" del productcontroller.php tengo que poner ni qué tengo que poner

 

y en el product.tpl  no sé como incluir un array combinations" ni se como mandarlo al product.js, tampoco sabria que tengo que poner en el product.js para que cambie dinamicamente en cuanto seleccione algo.

 

subo los archivos a ver si los quieren comprovar para saber si voy por buen camino ....

Desktop.zip

Link to comment
Share on other sites

1. Tienes que incluirlo en la query de la classe Product.php, funcion getAttributesGroups, en esa query, en ese select, añade la parte en color

 

product_attribute_shop.`minimal_quantity`, product_attribute_shop.`available_date`, ag.`group_type`, ag.`new_field`

 

 

 

2. En el ProductController.php en la funcion assignAttributesGroups, busca esta parte y añade el codigo en color

 

$combinations[$row['id_product_attribute']]['reference'] = $row['reference'];

$combinations[$row['id_product_attribute']]['new_field'] = $row['new_field'];

 

Lo ideal siempre que se sobreescriba una funcion es crear un archivo override con el contenido modificado

http://doc.prestashop.com/display/PS16/Overriding+default+behaviors

 

 

3. Ahora en el product.js en el combinationsJS añade la parte en color rojo

 

combinationsJS[k]['reference'] = combinations['reference'];

combinationsJS[k]['new_field'] = combinations['new_field'];

 

En el mismo archivo, en la function addCombination, añade el codigo de color en estas partes

 

function addCombination(idCombination, arrayOfIdAttributes, quantity, price, ecotax, id_image, reference, new_field, unit_price, minimal_quantity, available_date, combination_specific_price)

 

 

combination['reference'] = reference;

combination['new_field'] = new_field;

 

Un poco mas abajo, añade la parte de color

 

//get the data of product with these attributes

quantityAvailable = combination['quantity'];

selectedCombination['price'] = combination['price'];

selectedCombination['unit_price'] = combination['unit_price'];

selectedCombination['specific_price'] = combination['specific_price'];

selectedCombination['new_field'] = combination['new_field'];

if(selectedCombination['new_field']){

 

   $('#show_new_field').html("<label for='new_field'>"+newFieldLabel+'</label>'+"<p class='new_field'>"+selectedCombination['new_field']+'</p>').fadeIn('slow');

            } else {

            $('#show_impact_price').fadeOut('slow');

            }

 

 

 

4. Para que se visualice, añade en el product.tpl la parte en color

 

<!-- attributes -->

<div id="attributes">

<div id="show_new_field"> </div>

 

 

- Para hacer traducible la etiqueta añade en la parte de abajo del product.tpl, la parte en color rojo

 

{addJsDefL name=doesntExistNoMore}{l s='This product is no longer in stock' js=1}{/addJsDefL}

{addJsDefL name=newFieldLabel}{l s='New field' js=1}{/addJsDefL}

 

 

 

 

 

El resultado deberia ser algo parecido al que se muestra en la imagen adjunta

post-107989-0-69563800-1472754168_thumb.gif

  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...