1

How do I go about using a dynamic value to access a user field value? I have created a form builder for users and dynamically populate the user field based on the question's associated field.

<input name="fields[{{ question.fieldName }}]">

This works nicely but I am looking to pre-populate this input with a value if the user has previously provided and saved this info but I'm having trouble figuring out how to combine the field name with currentUser.

My first try was:

{% set fieldName = question.fieldName %}
{{ currentUser.fieldName }}

But that returns the following error:

Craft\UserModel and its behaviors do not have a method or closure named "fieldName".

Any help would be greatly appreciated

1 Answer 1

2

You could try using the attribute function in twig, this should let you call dynamic properties.

Something like:

{{ attribute(currentUser, question.fieldName) }}
3
  • Thanks for the suggestion, I tested it but get returned the following error: array_key_exists(): The first argument should be either a string or an integer Commented Apr 12, 2017 at 15:16
  • What values are you getting if you dump question.fieldName? Commented Apr 12, 2017 at 15:19
  • Sorry, using the attribute function did work. I just needed to to adjust it to use question.fieldName.value so I set that as a variable as such: {% set questionField = category.fieldName.value %} {{ attribute(currentUser, questionField ) }} Thanks! Commented Apr 12, 2017 at 18:54

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.