Skip to main content
Announcements
Have questions about Qlik Connect? Join us live on April 10th, at 11 AM ET: SIGN UP NOW
cancel
Showing results for 
Search instead for 
Did you mean: 
wdchristensen
Specialist
Specialist

User-defined functions equivalent in Qlik Sense

From time to time I find myself rewriting the same code over and over again. A simple example might be something like removing special characters that are not stripped by the default trim function.

Replace(Replace(myFieldName, char(194), ''), char(160), '')

Now suppose I want to make a custom trim that will accept a field name and perform a replace action. Ideally, I would like this new function to be usable in the load script and as well as in the application. How can this functionality be accomplished to prevent unnecessary code duplication.

1 Solution

Accepted Solutions
marcus_sommer

You could use a variable with parameters for it:

set eReplace = Replace(Replace($1, char(194), ''), char(160), '');

and then you call it:

...

$(eReplace(myFieldName)) as myFieldName

...

- Marcus

View solution in original post

5 Replies
marcus_sommer

You could use a variable with parameters for it:

set eReplace = Replace(Replace($1, char(194), ''), char(160), '');

and then you call it:

...

$(eReplace(myFieldName)) as myFieldName

...

- Marcus

wdchristensen
Specialist
Specialist
Author

Thanks for your reply. From what I can gather, this solution is for use in the load script. In my example this would probably work fine but in reality I am trying to show the truth evaluation for my set analysis conditions that I have put in variables as explained in another post (https://community.qlik.com/thread/261534?sr=stream).

So essentially I am repeating this measure formula 50 times:

=if((SUM({<$(vMarket)>} 2)) - (SUM({<1=1>} 1))=1,'True','False')

and I just keep changing vMarket to the next set analysis T/F condition. I am not sure I like this implementation so I really want to put it in a function so when I learn a better way I can make the change in one location and cascade the changes with as little rework as possible. Any suggestions?

rwunderlich
Partner Ambassador/MVP
Partner Ambassador/MVP

The solution Marcus proposed - variables with parameters - works in both load script and chart expressions.

-Rob

wdchristensen
Specialist
Specialist
Author

The first attempt I tried to put the definition in an application variable and noticed that the keyword "Set" was not recognized. Once I put the variable definition in the load script and then I was able to call the "function" in the application just as stated. As always, I appreciate the help!

Are there any examples that show this technique for more complex "functions"? For example, a for loop or do while loop...

rwunderlich
Partner Ambassador/MVP
Partner Ambassador/MVP

Unfortunately, you can't use the technique with loops (easily).  It needs to be a single expression, not a series of statements.

-Rob