!RtW: Make use of existing Formatters

This is going to be the first part of a new KTM series: Don’t re-invent the Wheel, or !RtW, as I will call it from now on.The goal of that series is to show you that most of the things in KTM come out-of-the box, very often you do not have to resort to scripting. The only thing you’ll need is just a little outside-of-the-box thinking, and I’d like to encourage you to do so. And if you come up with something interesting, I always look forward to hearing from you!

!RtW, part 1: use existing formatters

Scripting isn’t bad. In fact, I love doing it in KTM. The only thing that is bad is when you rebuilt something which already is present in KTM. In this first part I refer to formatting methods in particular: I did not know a single customer project where the built-in amount and date formatter did not suffice. However, I see lots of projects that contain custom scripts for formatting fields. Don’t do that! Even if you’d need a formatter in script, you still can make use of the existing formatting methods. In fact, what you can achieve:

  • Format a value, e.g an amount “2’530,22” –> “2500.00”
  • Check if formatting did work or not, e.g. “25d30.00” –> not possible to format, react

A sample use case could be the following: you fetch amounts from a database. Unfortunately, there are many different formats entered. And even worse, sometimes it contains even plain text! Well, no problem for our formatter: just set it up the way you are used to. Then, we make use of a temporary field and apply formatting there (remember: formatting rules are applied to fields).

So, that’s all we need:

  1. a (temporary) field
  2. a formatting method
  3. a short scripting

Here’s a sample script to get you started – I make use of a script locator for demo purposes:


Private Sub SL_Demo_LocateAlternatives(ByVal pXDoc As CASCADELib.CscXDocument, ByVal pLocator As CASCADELib.CscXDocField)

' this is the amount we recieve
Dim amnt As String
amnt = "2'530,22"
' this is our temporary field object (one-time use)
Dim tmpField As New CscXDocField

' let's make use of the already present formatter instead of coding our own
' we set the field's text to the amount we want to format..
tmpField.Text = amnt
' and now we call the default amount formatter set in the project properies
Project.FieldFormatters.ItemByName(Project.DefaultAmountFormatter).FormatField(tmpField)

' just for the sake of completeness, we set this demo script locator's one and only alternative
pLocator.Alternatives.Create
With pLocator.Alternatives.ItemByIndex(0)
.Confidence = 1
.Text = tmpField.Text
End With

' in case you need to check if formatting did work or not, just do the following
If tmpField.FormattingFailed Then
' your code
End If

End Sub

Here’s the result – mission achieved, we did not reinvent the wheel.

formatting