Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jaimestuardo opened this issue Mar 18, 2016 · 5 comments
Closed

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

jaimestuardo opened this issue Mar 18, 2016 · 5 comments

Comments

@jaimestuardo
Copy link

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

@piotrekkaminski
Copy link
Contributor

@elenleonova please check. Is this the correct way to check price format? I don't think so.

@veloraven
Copy link
Contributor

@jaimestuardo could you specify Magento version used?

@jibrandlr
Copy link

@veloraven This issue is present on 2.1.0 and 2.1.1. I've also reported the issue here: #6362

@andimov
Copy link
Contributor

andimov commented Sep 14, 2016

@lgarridoj
Thank you! So, I’m closing this issue because it is a duplicate.

@andimov andimov closed this as completed Sep 14, 2016
@mamunur34
Copy link

Hello,
I have stuck for this. After 3 days debugging, I got the solution from your post.

Thank You very much

magento-team pushed a commit that referenced this issue Mar 26, 2019
[TSG] Backporting for 2.1 (pr65) (2.1.17)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

10 participants