Skip to content

Price Format is overridden by a JavaScript in Product View #3834

Closed
@jaimestuardo

Description

@jaimestuardo

Hello,

I have changed price format in es.xml file that is located under zendframework1 folder. In my case, price format is something like this: $ 99.990

Well... after I made the change and wait some time for the changes to make effect, it worked in all the site, that is, price appears as I want but in product view page.

When I load product details page, I can see that the page is loaded with the corect price format, however, after about 0,5 seconds, the price changes to $99.990,00. It is curous, isn't it?

That behaviour suggested me that there is some JavaScript that something do with the price, so I saw page code using Firebug and I saw this code:

`<script>

require([
    'jquery',
    'Magento_Catalog/js/price-box'
], function($){
    var priceBoxes = $('[data-role=priceBox]');

    priceBoxes = priceBoxes.filter(function(index, elem){
        return !$(elem).find('.price-from').length;
    });

    priceBoxes.priceBox({'priceConfig': {"productId":"1","priceFormat":{"pattern":"$%s","precision":2,"requiredPrecision":2,"decimalSymbol":",","groupSymbol":".","groupLength":3,"integerRequired":1}}});
});

</script>`

After some investigation, I found that this piece of code is rendered in product/view/form.phtml template

When I opened it, I have found this code:

priceBoxes.priceBox({'priceConfig': <?php /* @escapeNotVerified */ echo $block->getJsonConfig() ?>});

Then, I opened block class file, finding this code:

` public function getJsonConfig()
{
/* @var $product \Magento\Catalog\Model\Product */
$product = $this->getProduct();

    if (!$this->hasOptions()) {
        $config = [
            'productId' => $product->getId(),
            'priceFormat' => $this->_localeFormat->getPriceFormat()
            ];
        return $this->_jsonEncoder->encode($config);
    }

    $tierPrices = [];
    $tierPricesList = $product->getPriceInfo()->getPrice('tier_price')->getTierPriceList();
    foreach ($tierPricesList as $tierPrice) {
        $tierPrices[] = $this->priceCurrency->convert($tierPrice['price']->getValue());
    }
    $config = [
        'productId' => $product->getId(),
        'priceFormat' => $this->_localeFormat->getPriceFormat(),
        'prices' => [
            'oldPrice' => [
                'amount' => $this->priceCurrency->convert(
                    $product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue()
                ),
                'adjustments' => []
            ],
            'basePrice' => [
                'amount' => $this->priceCurrency->convert(
                    $product->getPriceInfo()->getPrice('final_price')->getAmount()->getBaseAmount()
                ),
                'adjustments' => []
            ],
            'finalPrice' => [
                'amount' => $this->priceCurrency->convert(
                    $product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue()
                ),
                'adjustments' => []
            ]
        ],
        'idSuffix' => '_clone',
        'tierPrices' => $tierPrices
    ];

    $responseObject = new \Magento\Framework\DataObject();
    $this->_eventManager->dispatch('catalog_product_view_config', ['response_object' => $responseObject]);
    if (is_array($responseObject->getAdditionalOptions())) {
        foreach ($responseObject->getAdditionalOptions() as $option => $value) {
            $config[$option] = $value;
        }
    }

    return $this->_jsonEncoder->encode($config);
}

`
I can see that price format is retrieved in $this->_localeFormat->getPriceFormat().

Finally, I have opened framework/Locale/Format.php file to see this code:

` /**
* Functions returns array with price formatting info
*
* @param string $localeCode Locale code.
* @param string $currencyCode Currency code.
* @return array
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function getPriceFormat($localeCode = null, $currencyCode = null)
{
$localeCode = $localeCode ?: $this->_localeResolver->getLocale();
if ($currencyCode) {
$currency = $this->currencyFactory->create()->load($currencyCode);
} else {
$currency = $this->_scopeResolver->getScope()->getCurrentCurrency();
}
$localeData = (new DataBundle())->get($localeCode);
$format = $localeData['NumberElements']['latn']['patterns']['currencyFormat']
?: explode(';', $localeData['NumberPatterns'][1])[0];
$decimalSymbol = $localeData['NumberElements']['latn']['symbols']['decimal']
?: $localeData['NumberElements'][0];
$groupSymbol = $localeData['NumberElements']['latn']['symbols']['group']
?: $localeData['NumberElements'][1];

    $pos = strpos($format, ';');
    if ($pos !== false) {
        $format = substr($format, 0, $pos);
    }
    $format = preg_replace("/[^0\#\.,]/", "", $format);
    $totalPrecision = 0;
    $decimalPoint = strpos($format, '.');
    if ($decimalPoint !== false) {
        $totalPrecision = strlen($format) - (strrpos($format, '.') + 1);
    } else {
        $decimalPoint = strlen($format);
    }
    $requiredPrecision = $totalPrecision;
    $t = substr($format, $decimalPoint);
    $pos = strpos($t, '#');
    if ($pos !== false) {
        $requiredPrecision = strlen($t) - $pos - $totalPrecision;
    }

    if (strrpos($format, ',') !== false) {
        $group = $decimalPoint - strrpos($format, ',') - 1;
    } else {
        $group = strrpos($format, '.');
    }
    $integerRequired = strpos($format, '.') - strpos($format, '0');

    $result = [
        //TODO: change interface
        'pattern' => $currency->getOutputFormat(),
        'precision' => $totalPrecision,
        'requiredPrecision' => $requiredPrecision,
        'decimalSymbol' => $decimalSymbol,
        'groupSymbol' => $groupSymbol,
        'groupLength' => $group,
        'integerRequired' => $integerRequired,
    ];

    return $result;
}`

The line $localeData = (new DataBundle())->get($localeCode); passes "es_ES" as the locale which is getting wrong locale values, not the values configured in es.xml file of Zendframework1.

I have used this code in Format.php to test:

$localeData = (new DataBundle())->get($localeCode); print_r($localeData['NumberPatterns'][1]); die;
With that, I checked that with the locale code "es_ES", this format is returned: ¤ #,##0.00. That format is not set in es_ES because if I see es_ES.xml file, this appears:

`

` I think this needs to be changed so that if could get the correct format as the whole site does.

Regards
Jaime

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions