I have a point layer with three fields: "species" (text string) , "number" (integer 64 bit) and "text" (text string).
For every unique value in "species", "number" starts with value '1' and goes up to '1+x'.
I want to auto increment the value in "number" by 1 for every new feature I add that has the same unique value in "species".
From searching the forum I came up with this solution:
- in field configuration I set the default value for "number" by using expression:
format('%1', with_variable ('n', array_count(array_agg("species"), "species") + 1, lpad(@n, 3, '0')))
- tick the check box for "apply default value on update"
This works quite well until I afterwards make changes to the values in the "text" field. Then the default value gets updated for all features with the same unique value in "species". It gets updated to x+1 where x is the highest number that was automatically created by adding the last feature of a certain "species".
How can I avoid that without simply unchecking the box for "apply default value on update" for the field "number"?
-
I think you need to uncheck "apply default value on update" for the field "number" not "species". That way it should only run the expression when the feature is first created and not everytime it is updatedThatMikaTho– ThatMikaTho2025年06月23日 18:02:10 +00:00Commented Jun 23 at 18:02
-
Ah sorry that was a mistake in the question. I corrected it. Unchecking this Option for the Field „number" is Not working because I add species Name After species Name in the „species" Field. If I Would uncheck „Apply default value on update" After I am ready with the First species, the whole procedure does Not work anymore for the following species I add. I Hope I am able to describe sufficiently What I mean.Hannes– Hannes2025年06月23日 20:35:56 +00:00Commented Jun 23 at 20:35
1 Answer 1
You can use a CASE WHEN clause in the setup for the default value. This way you can leave the "Apply default value on update" checked
CASE
WHEN "number" IS NULL THEN <your expression>
ELSE "number"
END
Everytime you update your feature the expression checks if "number" is null or not. If "number" is null (e.g. upon creation of the feature) your expression will be used to compute the respective number. And if it is not null (e.g. while editing the "text" field) the existing value is used.
-
Yay! So easy and yet so effective! It's this kind of logical thinking I am just not capable of :-D Thanks a lot!Hannes– Hannes2025年06月24日 08:05:19 +00:00Commented Jun 24 at 8:05
-
If I'm not mistaken, this works best if a valid "species" value is immediately selected via a drop-down box or similar. If the "species" value is something you start typing out, the expression will automatically assign a value of probably 1 (because the first few letters won't match any other "species" value), and then it won't change again after that because "number" is not null.she_weeds– she_weeds2025年06月24日 12:52:28 +00:00Commented Jun 24 at 12:52