TransWikia.com

QGIS set fixed ID name with autoincrement in data attribute table

Geographic Information Systems Asked on April 19, 2021

I am going to create a bulk of lines in QGIS.
One line will have allocated ID, which looks as follows:

DT.C.10_Strand

Thereafter each "Strand" will have the number of order like you see below:

enter image description here

After adding a new row I need to increment my ID number by one.

How can I define it in advance? Is there any solution in i.e. field calculator or somewhere?
So far I have to write down every time the ID name. Can I have it ready and only change the number? or increment id as we can do in Excel?

One Answer

Open the layer properties and go to the Attributes Form tab on the left.

Select the "ID" field and go down to Defaults.

We're going to add an expression here to auto-increment the field. This would be easier if it was just a numeric field but because it is a text string it will take a little more fine-tuning, but that's OK.

Before I get into it, the idea is that we're going to extract the numeric part of the string and convert it to an actual number. That way we can find out what the current max is and then increment that. Then we'll add that back on to the generic string. But we have to be careful when doing that because of the leading zeroes. Also because this will need to be set to auto-update, we have to add a catch to prevent it overwriting pre-existing IDs if you edit those features.

So the expression box add the following expression:

IF("ID" IS NULL, --this checks if there is already an ID value

'DT.C.10_Strand_' || lpad(to_string(maximum(to_int(right("ID", 3)))+1), 3, '0'), --this section adds the incremented number, padded to the left for leading zeroes

"ID") --this is in case there is already an existing ID

Then make sure the Apply default value on update box is checked.

EDIT: I see @Taras has added a comment which might be more elegant than my hacky code

EDIT 2: I was inspired by @Taras's better code to update my answer, thanks @Taras.

Correct answer by TeddyTedTed on April 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP