First add a numerical field named id
or whatever you wish to your layer.
Then open the layer properties and navigate to "Attributes form".
Select your id field and scroll down to default. Add array_length(array_agg(@id))+1
as expression. You can also uncheck "editable" to prevent it from beeing edited by user or change the widget type to "hidden" to not even show it when adding features.
Note that @id
or $id
do not work here because these values will be assigned after a feature is added, and are therefore not available while adding a feature.
Also not that array_length(array_agg(@id))+1
may produce duplicates if you delete features. In that case you may want to use something like array_max(array_agg("id"))+1
instead. Note that here @id
has been replaced by the field "id"
. Note that here you may get gaps in your id sequence if you delete features.
Also consider to use the options "Unique" or "Not null" if you want to show a hint in case the rule is about to be broken.
$id
?