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?
1 Answer 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>
)
),
' ',
', '
)
-
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.nintskari– nintskari2018年08月16日 08:18:08 +00:00Commented 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?geozelot– geozelot2018年08月16日 08:42:27 +00:00Commented Aug 16, 2018 at 8:42
null
, then there'd be a comma at the beginning...@nintskari, did you try the Expression Dialog?