QGIS Auto-increment ID – Fixing Issues in Data Attribute Table for String Columns

attribute-tableexpressionqgis

By following this question:

QGIS set fixed ID name with autoincrement in data attribute table

I tried to prepare the formula, which could let me increment the very last number in the string.

The ID is: VON/FLN/CBF-DU2/A1/VP.1 and I need the increment like:
VON/FLN/CBF-DU2/A1/VP.2,
VON/FLN/CBF-DU2/A1/VP.3,
VON/FLN/CBF-DU2/A1/VP.4, etc

So far, my formula looks as follows:

'VON/FLN/CBF-DU2/A1/VP.' || lpad(to_string(maximum(to_int(right("ID", 3)))+1), 3, '0')

but it keeps throwing the NULL value in my data attribute table.

The same is with the following formula:

'VON/FLN/CBF-DU2/A1/VP.' ||  lpad("pkuid", '3', '0')

and this one

IF("ID" IS NULL, 'VON/FLN/CBF-DU2/A1/VP.' || lpad(to_string(maximum(to_int(right("ID", 3)))+1), 3, '0'), "ID")

Does anyone know where might be the problem?

How to use the

lpad

function effectively?

enter image description here

UPDATE:

   IF("ID" IS NULL, 'VON/FLN/CBF-DU2/A1/VP.' || 
   lpad(to_string(maximum(to_int(right("ID", 1)))+1), 2, '0'), "ID")

After changing the "ID", 3 to "ID", 1 the formula has started to work. Could anyone explain what do these values mean? Considering that they bounded with function right and to_int?

Best Answer

I am not an expression expert, but I think the following script helps:

layer = iface.activeLayer()

layer.dataProvider().addAttributes([QgsField("ID", QVariant.String, len=50)])
layer.updateFields()

layer.startEditing()
request = QgsFeatureRequest().addOrderBy("pkuid")
for i, feat in enumerate(layer.getFeatures(request)):
    lpad = f'{i+1:03}' # returns 001, 010, 099, 100, ..
    feat["ID"] = 'VON/FLN/CBF-DU2/A1/VP.' + lpad
    layer.updateFeature(feat)
    
layer.commitChanges()

enter image description here

Related Question