1

Is it possible to use a local variable in a label expression/field calculator in QGIS 3? I have an extremely long CASE expression that generates a String for the labels of my objects, and I would like to process the string after I have generated it. To do this, however, I would need to save the string in a local variable and refer to the variable in the processing afterwards.

Here's a shortened version of my problem:

CASE when ("A" != 'null' then 'A: ' || "A" || ', ' else '' end ||
CASE when ("B" != 'null' then 'B: ' || "B" || ', ' else '' end ||
CASE when ("C" != 'null' then 'C: ' || "C" || ', ' else '' end

This creates something like: "A: 3, B: 1, "

There's ", " always after the last variable and I would like to remove that from the end. The expression I'm using is so long that it exceeds the character limit of the field calculator. That's why I would like to save the string in a local variable "input", then use left(input, length(input) - 2). This would delete the last two ", " and make the string "A: 3, B: 1". It will have to be done like this because the table will be updated in the future.

Is this possible?

asked Aug 9, 2018 at 14:22
2
  • 1
    Why not reword your expression so that the comma only appears with the second CASE statement? so when "A" != null then 'A: ' || "A"; case when B != null then ', B: ' || "B" .. .and so on Commented Aug 13, 2018 at 1:29
  • 1
    @she_weeds if "A" is null, then there'd be a comma at the beginning...@nintskari, did you try the Expression Dialog? Commented Aug 15, 2018 at 7:55

1 Answer 1

1

If you use the Expression Dialog in the Labels tab of the layer properties, you can add CASE expressions till the end of days...

Use double spaces following each string, trim() the trailing and replace() the others with ,:

replace(
 trim(
 concat(
 CASE WHEN "A" != 'null' THEN 'A: ' || "A" || ' ' ELSE NULL END,
 <add_till_fingers_bleed>
 )
 ),
 ' ',
 ', '
)
answered Aug 10, 2018 at 12:28
2
  • Thank you! That actually does work! But I used a different workaround. I made it so that the ", " is at the beginning, then used trim(). Apparently, the length of trim() function doesn't have to be precise, so I could just use it to trim the first two characters. Commented Aug 16, 2018 at 8:18
  • @nintskari glad you found your way. just asking: trim() explicitly removes whitespaces at the start and end of a string...are you sure that those leading commas are removed? Commented Aug 16, 2018 at 8:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.