Giter Club home page Giter Club logo

Comments (5)

dosubot avatar dosubot commented on July 23, 2024 2

Hello, @duyhd! I'm here to help you with any issues, bugs, or questions you may have. I can also guide you on becoming a contributor. Let's work together to solve this!

To change the number format in Apache Superset from "226,049,182,616.69₫" to "226.049.182.616,69₫", you need to set a custom D3 format locale. This can be done using the setD3Format function provided in the NumberFormatterRegistrySingleton.ts file.

Here is an example of how you can set the D3 format locale to achieve the desired number format:

import { setD3Format } from 'path-to-NumberFormatterRegistrySingleton';

const vietnameseLocale = {
  decimal: ',',
  thousands: '.',
  grouping: [3],
  currency: ['₫', ''],
};

setD3Format(vietnameseLocale);

This code sets the decimal separator to a comma (,), the thousands separator to a period (.), and specifies the currency symbol for Vietnamese đồng (₫). After setting this locale, numbers will be formatted as "226.049.182.616,69₫" [1][2].

Additionally, you can use the @superset-ui/number-format package to validate and preview the number format. Here is an example of how you can use this package:

import { PureComponent } from 'react';
import { formatNumber } from '@superset-ui/core';

class NumberFormatValidator extends PureComponent {
  state: { formatString: string; testValues: (number | null | undefined)[] } = {
    formatString: '.3~s',
    testValues: [
      987654321,
      12345.6789,
      3000,
      400.14,
      70.00002,
      1,
      0,
      -1,
      -70.00002,
      -400.14,
      -3000,
      -12345.6789,
      -987654321,
      Number.POSITIVE_INFINITY,
      Number.NEGATIVE_INFINITY,
      NaN,
      null,
      undefined,
    ],
  };

  constructor(props) {
    super(props);
    this.handleFormatChange = this.handleFormatChange.bind(this);
  }

  handleFormatChange(event) {
    this.setState({
      formatString: event.target.value,
    });
  }

  render() {
    const { formatString, testValues } = this.state;

    return (
      <div className="container">
        <div className="row" style={{ margin: '40px 20px 0 20px' }}>
          <div className="col-sm">
            <p>
              This <code>@superset-ui/number-format</code> package enriches{' '}
              <code>d3-format</code>
              to handle invalid formats as well as edge case values. Use the
              validator below to preview outputs from the specified format
              string. See
              <a
                href="https://github.com/d3/d3-format#locale_format"
                target="_blank"
                rel="noopener noreferrer"
              >
                D3 Format Reference
              </a>
              for how to write a D3 format string.
            </p>
          </div>
        </div>
        <div className="row" style={{ margin: '10px 0 30px 0' }}>
          <div className="col-sm" />
          <div className="col-sm-8">
            <div className="form">
              <div className="form-group">
                <label>
                  Enter D3 format string:
                  <input
                    id="formatString"
                    className="form-control form-control-lg"
                    type="text"
                    value={formatString}
                    onChange={this.handleFormatChange}
                  />
                </label>
              </div>
            </div>
          </div>
          <div className="col-sm" />
        </div>
        <div className="row">
          <div className="col-sm">
            <table className="table table-striped table-sm">
              <thead>
                <tr>
                  <th>Input (number)</th>
                  <th>Formatted output (string)</th>
                </tr>
              </thead>
              <tbody>
                {testValues.map((v, index) => (
                  <tr key={index}>
                    <td>
                      <code>{`${v}`}</code>
                    </td>
                    <td>
                      <code>&quot;{formatNumber(formatString, v)}&quot;</code>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    );
  }
}

export default {
  title: 'Core Packages/@superset-ui-number-format',
};

export const validator = () => <NumberFormatValidator />;

This example demonstrates how to use the @superset-ui/number-format package to validate and preview the number format changes [2].

To continue talking to Dosu, mention @dosu.

from superset.

dosubot avatar dosubot commented on July 23, 2024 2

To convert the currency format and fetch data from your customized Super Dashboard page using the superset-ui/embedded-sdk, follow these steps:

  1. Convert Currency Format:
    Use JavaScript to convert the number format. Here is a function to achieve this:

    function convertNumberFormat(numberString) {
      // Remove the currency symbol
      let number = numberString.replace('₫', '').trim();
      
      // Replace commas with temporary placeholder
      number = number.replace(/,/g, '_');
      
      // Replace dots with commas
      number = number.replace(/\./g, ',');
      
      // Replace temporary placeholder with dots
      number = number.replace(/_/g, '.');
      
      // Add the currency symbol back
      return number + '₫';
    }
    
    const formattedNumber = convertNumberFormat("226,049,182,616.69₫");
    console.log(formattedNumber); // Output: "226.049.182.616,69₫"
  2. Fetch Data from Customized Super Dashboard:
    Use the embedDashboard function from the superset-ui/embedded-sdk to embed and fetch data from your customized Super Dashboard page. Here is an example:

    import { embedDashboard } from "@superset-ui/embedded-sdk";
    
    async function fetchGuestTokenFromBackend() {
      // Implement the logic to fetch the guest token from your backend
      const response = await fetch('/your-backend-endpoint-to-get-guest-token');
      const data = await response.json();
      return data.guestToken;
    }
    
    embedDashboard({
      id: "abc123", // Replace with your actual dashboard ID
      supersetDomain: "https://superset.example.com", // Replace with your Superset domain
      mountPoint: document.getElementById("my-superset-container"), // Replace with your actual mount point
      fetchGuestToken: fetchGuestTokenFromBackend,
      dashboardUiConfig: {
        hideTitle: true,
        filters: {
          expanded: true,
        },
        urlParams: {
          foo: 'value1',
          bar: 'value2',
          // Add other URL parameters as needed
        }
      },
    });

Additionally, you can leverage the NumberFormatterRegistrySingleton from superset-ui-core to handle number formatting more robustly:

import { getNumberFormatter, setD3Format } from '@superset-ui/core';

// Define a custom locale for number formatting
const customLocale = {
  decimal: ',',
  thousands: '.',
  grouping: [3],
  currency: ['₫', ''],
};

// Set the custom locale
setD3Format(customLocale);

// Get the formatter
const formatter = getNumberFormatter(',.2f');

// Format the number
const formattedNumber = formatter(226049182616.69);
console.log(formattedNumber); // Output: "226.049.182.616,69₫"

By following these steps, you can convert the currency format and embed your customized Super Dashboard page using the superset-ui/embedded-sdk [1][2].

To continue talking to Dosu, mention @dosu.

from superset.

dosubot avatar dosubot commented on July 23, 2024 2

To pass the formatNumber function into the embedDashboard function, you can integrate it directly within the dashboard embedding logic. Here's an example of how to do this:

  1. Import the formatNumber function from @superset-ui/core.
  2. Define the formatNumberValue function to format numbers using the desired format.
  3. Use the formatNumberValue function within the embedDashboard logic.

Here is the complete example:

import { embedDashboard } from "@superset-ui/embedded-sdk";
import { formatNumber } from '@superset-ui/core'; // Ensure you have the correct import

async function fetchGuestTokenFromBackend() {
  // Implement the logic to fetch the guest token from your backend
  const response = await fetch('/your-backend-endpoint-to-get-guest-token');
  const data = await response.json();
  return data.guestToken;
}

function embedCustomDashboard() {
  const currencyFormat = ',.2f'; // Define your desired format

  function formatNumberValue(value) {
    return formatNumber(currencyFormat, value);
  }

  embedDashboard({
    id: "abc123", // Replace with your actual dashboard ID
    supersetDomain: "https://superset.example.com", // Replace with your Superset domain
    mountPoint: document.getElementById("my-superset-container"), // Replace with your actual mount point
    fetchGuestToken: fetchGuestTokenFromBackend,
    dashboardUiConfig: {
      hideTitle: true,
      filters: {
        expanded: true,
      },
      urlParams: {
        foo: 'value1',
        bar: 'value2',
        // Add other URL parameters as needed
      }
    },
    onDataLoad: (data) => {
      // Example usage of formatNumberValue within the dashboard embedding logic
      data.forEach(item => {
        item.formattedValue = formatNumberValue(item.value);
      });
      console.log(data); // This will print the formatted data
    }
  });
}

embedCustomDashboard();

In this example:

  • The formatNumber function is used to format numbers according to the specified currencyFormat.
  • The onDataLoad callback in the embedDashboard function processes the data and applies the custom number formatting.

This approach ensures that the currency format is correctly applied within the embedded dashboard [1][2].

To continue talking to Dosu, mention @dosu.

from superset.

duyhd avatar duyhd commented on July 23, 2024

@dosu
If I use superset-ui/embedded-sdk, is there a way to convert currency as I require and fetch data from my customized Super Dashboard page?"

Would you like assistance with converting currency and fetching data using superset-ui/embedded-sdk?
Here is the UI page I use to retrieve data.
image

from superset.

duyhd avatar duyhd commented on July 23, 2024

You're asking how to pass the formatNumber function into embedDashboard like the example I sent you earlier, right?

from superset.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.