0

I've created a series of layers in QGIS to collect data in field with mobile app QField. Each layer have a rule to make its names.

For example, one layer is modeled to collect corn fields. It has several attributes and its name field should be filled with value C1 for the first point, C2 for the next one and so on. I need to set the layer form with autofill sequentially. If I registered four corn points, I'll have C1, C2, C3, and C4. Once the user in field mark another corn points, the app show the form with the fifth point autofilled with C5, unique, not null and read-only. Later, the user has to delete C2 and the latest points (C3, C4 and C5) got automatically updated to minus one unit (C2, C3, C4).

I've tried to create the name field as a virtual field and use the expression 'C' + @row_number but apparently, @row_number only works with regular fields. In the Attributes Form I got no options for that, not even a PyQGis approach in the internet.

Any ideas?

1
  • Be careful with pyqgis tag, without a piece of code your question can be closed ...
    – Taras
    May 24, 2022 at 5:17

1 Answer 1

1

'C'||if(count(@layer_id)=0,1,maximum("name")+1)

the source of knowledge: https://stuyts.xyz/2019/10/31/how-to-autonumber-a-field-in-qgis/


Here are the triggers Oisin mentioned:

  • CREATE TRIGGER YOUR-TABLE-NAME_keep_in_order_delete AFTER DELETE ON YOUR-TABLE-NAME BEGIN UPDATE YOUR-TABLE-NAME SET name_id = name_id-1 WHERE name_id > old.name_id; END (https://sqlite-users.sqlite.narkive.com/gdABXzam/sqlite-sql-to-renumber-values-in-a-column#post4)

  • CREATE TRIGGER YOUR-TABLE-NAME_populate_name AFTER INSERT ON YOUR-TABLE-NAME BEGIN UPDATE YOUR-TABLE-NAME SET name = (SELECT 'C'|| "name_id") WHERE name_id = NEW.name_id; END

  • CREATE TRIGGER YOUR-TABLE-NAME_update_name AFTER UPDATE OF name_id ON YOUR-TABLE-NAME BEGIN UPDATE YOUR-TABLE-NAME SET name = (SELECT 'C'|| "name_id") WHERE OLD.name_id > NEW.name_id; END

With sqlitebrowser you can easily insert them into the database (ex.: geopackage). (https://sqlitebrowser.org/)

Required columns in the database:

name_id INTEGER UNIQUE

name TEXT UNIQUE

In QGIS you have to use for default value: if(count(@layer_id)=0,1,maximum("name_id")+1) , but don't check "Apply default value on update"

ps. Tested with qfield, and :)))

1
  • This does not renumber after record deletion. The only way i envisage this coukd be done is with a sql trigger statement, providing this is supported by the layer type. Even then the sql is beyond me
    – Oisin
    May 26, 2022 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.