1

I'm trying to auto-increment a field "ID-Station" by using an expression. The expression depends on another field, "Sampler".

These are my fields :

  • Sampler : picklist with Sampler_A, Sampler_B, ...
  • ID_Station : Should be Sampler_A-001 and then Sampler_A-002 or Sampler_B-001

I try with this expression :

coalesce("sampler") || '-' || coalesce(lpad((count( "sampler",("sampler"))+1),3,0)))

It works fine on QGIS. But in QField, because the default value is applying on update, all my stations are renamed automatically in background. For example, if I had three stations (Sampler_A-001, 002 and 003), every three stations become Sampler_A-003.

Is there a way to avoid this problem?

4
  • Untick 'apply on update'
    – Oisin
    Commented Aug 22, 2023 at 14:26
  • Try changing the condition to "ID-Station" = '' instead of "ID-Station" is NULL
    – Mayo
    Commented Aug 23, 2023 at 18:46
  • If I untick 'apply on update', the expression isn't working at all.
    – Fred
    Commented Aug 24, 2023 at 20:43
  • By changing is NULL by '', it is not working. By default, the field is filled with "NULL" that appears in italics.
    – Fred
    Commented Aug 24, 2023 at 20:50

1 Answer 1

0

Use your expressions within a condition, so you only apply it when the "ID-Station" field is empty.

if(
  "ID-Station" is NULL,
  coalesce("sampler") || '-' || coalesce(
    lpad(
      count("sampler", "sampler") + 1,
      3,
      0
    )
  ),
  "ID-Station" -- else
)
3
  • Thanks for your help. Adding a condition works fine. It is the idea I was looking for. But it's not working completely. If I edit my station to modify a field (for exemple, a sample_number field, doesn't matter), the form updates and even if ID_Station is not NULL, the expression runs anyway and the ID_Station becomes wrong. So I still need something to block the update.
    – Fred
    Commented Aug 23, 2023 at 23:25
  • Easy to overcome in QGIS with some Python, but difficult for QField, with only expressions available. I think the key is how you number your stations. If, for instance, they are numbered in order of recording them in QField, you could use a datetime field to store the creation date (and a seperate field for modified date with 'auto update' checked). You can then use array_agg(), as per my answer here: gis.stackexchange.com/a/465832/111101...
    – Oisin
    Commented Aug 28, 2023 at 16:42
  • ...However, in QField, if you then change something, even with 'auto update' checked, only edited records get updated. Perhaps you need to consider what you need in the field and what you need in QGIS. Perhaps this is a task that can be done in the office on QGIS only? If so, a Python script will sort this out.
    – Oisin
    Commented Aug 28, 2023 at 16:42

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.