3

I made a simple graphical model:

A Vector Layer input with a corresponding Vector Field vf input. A Field Calculator is used to calculate a new field's value based on the selected Vector Field's value of each feature using the expression

CASE
  WHEN @vf = 'foo' THEN 1 
  ELSE 0
END

The user is supposed to pick a layer and a field of that layer. A new "boolean" integer field is calculated then, set to 1 if the selected field matches a certain condition and 0 if not.

I always get a 0 as result. It also does not work if I use a if() function instead of the CASE statement. It also does not work if I surround the @vf with double quotes: WHEN "@vf" ...

It works if I reproduce the same workflow manually without a model, substituting the @vf in the expression with the actual field name of course.

How can I get this seemingly simple Field Calculator expression to work correctly?

2
  • 1
    If Vector Field is a Field, you have to use double quotes " --> "vf" in your expression Commented Aug 19, 2022 at 12:35
  • 1
    @vf references the variable the model input Vector Field (I named mine "vf") returns. Double quotes around it made no difference. "vf" does not work as there is no field literally named "vf". Commented Aug 19, 2022 at 16:55

1 Answer 1

4

While I am not sure what the actual cause of trouble is (see below) I managed to solve it by using the attribute() function to get the field's value by specifying the field name as a string:

CASE
  WHEN attribute(@vf) = 'foo' THEN 1 
  ELSE 0
END

Thoughts on the technical background

I suspect it is something about the Vector Field output being an unquoted string and the Field Calculator is not recognising it as reference to a field. If I use eval() to eval a concatenated string of " + field name + " it works.

CASE
  WHEN eval('"' || @vf || '"') = 'foo' THEN 1
  ELSE 0
END

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.