Creating Custom Formatters (PHP and client-side)

I have been trying to supplement the native formatters in Wappler and found that most things can be added by using custom formatters. What I found, though was the technique for this was hidden in answers to specific questions so thought a short tutorial may help some:

Server-side (php)

  1. In dmxConnectLib/lib/formatters create a file, call it something like customformatters.php (do not alter the native files as it could be overwritten with updates)
  2. Add the relevant code:
    the function name should be preceded by ‘formatter_’ and return the formatted value.
    e.g.
    <?php namespace lib\core; function formatter_stringify($val){ $retval = json_encode($val); return $retval; } ?>
  3. Save and upload the custom formatter file to the server
  4. Use the formatter in your insert statement:

(in the above example q_json represents the API/DB query response and stringify is the function name)

Client-Side

  1. Create a file called something like customformatters.js
  2. Include the file on your page
    <script src="js/customformatters.js"></script> (if you created it in a folder called js - alter the path as appropriate)
  3. If the formatter you wish to use takes advantage of an external library (e.g. cryptojs), include that on your page too
    e.g.
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
  4. In the formatter file create the formatter entries:
    e.g.
    dmx.Formatter('string', 'md5', function(val) { return CryptoJS.MD5(val); });
  5. You can then use the formatter on a variable in main code view UI or in the data-picker code view.
    e.g. {{someval.md5()}}

If the formatter needs more parameters than the value being formatted, add them to the formatter function. The first is always the value the formatter is being applied to and extras can be added inside the brackets. e.g.
dmx.Formatter('string', 'aesenc', function (val, sec) { var retval = CryptoJS.AES.encrypt(val, sec); return retval.toString(); });
can be called with
{{someval.aesenc(somesecretkey)}}

I hope this helps. It has certainly expanded what I thought was possible - which was already pretty limitless…

10 Likes

Thanks! This was super useful to create a custom client side url encode formatter.

dmx.Formatter('string', 'urlEncode', function (val) { return encodeURI(val); });

1 Like