Question

In Magento version 2.3.2 and 2.3.3, in a UI form, I have a field element input, of type price*:

<field formElement="input" name="price" sortOrder="60">
    <settings>
        <dataType>price</dataType>
        <label translate="true">Price</label>
        <dataScope>price</dataScope>
        <validation>
            <rule name="required-entry" xsi:type="boolean">false</rule>
        </validation>
        <additionalClasses>
            <class name="admin__field-medium">true</class>
        </additionalClasses>
    </settings>
</field>

Looks like this:

enter image description here

Here, I found documentation for field types, from UI form.

I want the price in that field to be displayed with two decimal places, “10.00” instead of “10.0000”.

Was it helpful?

Solution

In order to format the price, from a field in UI form, it is necessary to extend the component Magento_Ui/js/form/element/abstract that has actions on the elements of a UI form - in our case we overwrite the setInitialValue method from Magento_Ui/js/form/element/abstract in our component.

To format the price, we will use another component in our Magento_Catalog/js/price-utils component which deals with the formatting of the price, with the formatPrice method.


The component for price formatting is created in the module developed in view/adminhtml/web/js/format-price.js which contains the following code:

define([
  'Magento_Ui/js/form/element/abstract',
  'Magento_Catalog/js/price-utils'
], function (Element, priceUtils) {
  'use strict';

  return Element.extend({
    defaults: {
      'defaultText': '',
    },
    setInitialValue: function() {
      this._super();
      var self = this;

      self.setFormatPrice(self.initialValue);
      return this;
    },

    setFormatPrice: function(value) {
      var price = (value) ? priceUtils.formatPrice(value) : this.defaultText;
      this.initialValue = price;
      this.value._latestValue = price;

      return this;
    }
  });
});

In the file where you declared the field in the UI form, it is necessary to call your component VendorName_ModuleName/js/format-price and specify the method used to set the value in the field setInitialValue, see below:

<field formElement="input" name="price" component="VendorName_ModuleName/js/format-price" sortOrder="60">
    <settings>
        <dataType>price</dataType>
        <label translate="true">Price</label>
        <dataScope>price</dataScope>
        <validation>
            <rule name="required-entry" xsi:type="boolean">false</rule>
        </validation>
        <additionalClasses>
            <class name="admin__field-medium">true</class>
        </additionalClasses>
        <imports>
            <link name="setInitialValue" />
        </imports>
    </settings>
</field>

See the result from screenshot:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top