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

2

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

Something like:

{{ attribute(currentUser, question.fieldName) }}
  • 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 – ChocolateOrange Apr 12 '17 at 15:16
  • What values are you getting if you dump question.fieldName? – Alec Ritson Apr 12 '17 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! – ChocolateOrange Apr 12 '17 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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