I tried the attribute twig function for this but that did not work.

Essentially, what I'd like to achieve is the following:

{# This string variable is a name of the object #}
{% set myForm = 'form' %}
{# I'd like to call the 'errors' method on the 'form' object #}
{% set formErrors = myForm.errors %}

The problem with the above code is that the errors method will be called on the myForm object instead of the form object.

Is there any way to achieve what I'm trying to do here?

  • 1
    Can you explain why you have a string that represents the object?
    – carlcs
    Jul 11 '14 at 15:14

I've run into a similar situation. I was able to get things working in my situation using Twig's _context variable. The object I needed was available to the page, but the object name was only known as a string on the page.

I set the object on the page, by accessing it with the string I had via the _context object. _context is a Global Variable in Twig, which contains all currently defined variables on the page. This made sure that I was accessing the form object being returned to the page (not redefining the object from the database).

{% set submittedFormModel = (_context[entry.formField.first().handle] is defined 
                            ? _context[entry.formField.first().handle] 
                            : null) %}

From there, I could access the errors via Twig's attribute function:

{% set errors = attribute(submittedFormModel, 'getErrors') %}

{% for error in errors %}
{% endfor %}

Or, via the object as normal:

{% for error in submittedFormModel.getErrors() %}
{% endfor %}

Twig's attribute function allows you to set the method as a string and not the object. The object has to be an actual object, even with that function.

{% set object = craft.entries.order('postdate').last() %}
{% set method = 'title' %}

{{ attribute(object, method) }}

The only workaround I can think of is to link your object-representing string to an actual object in your template. But this makes little sense as you probably wouldn't have set it as a string to begin with, hehe. Anyways:

{% if string == "craft.entries.order('postdate').last()" %}
    {% set object = craft.entries.order('postdate').last() %}
{% endif %}

{{ attribute(object, method) }}

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.