phalcon : volt get value from array which key taken from variable
Solution 1
While frustrated tinkering with volt extension, I found a simpler solution :
Convert the model object into array. In the controller :
$products->toArray()
Simply, in the view, to display specific value of specific key from an array :
{{ product[key] }}
Problem solved, though because it is now not in form of object, I can't access object property using dot like {{ product.some_field }}
, instead {{ product['some_field'] }}
.
Solution 2
You should use the readAttribute() function: http://forum.phalconphp.com/discussion/1231/volt-access-to-object-property-using-variable
{{ product.readAttribute(col) }}
AzDesign
Updated on June 22, 2022Comments
-
AzDesign almost 2 years
In phalcon templating engine volt (which is similar to twig) you can fetch all records by :
{% for product in products %} Name: {{ product.name }} Description: {{ product.description }} price: {{ product.price}} {% endfor %}
So, in my scenario, I'm building a crud template which will be used for different kind of models. What I wanted to achieve in this template is that every columns in this view are not hard-coded. So I store the columns I wanted to show into an array (defined in the controller, passed to the view) :
$cols = ['name','description','price']
In the view, to make it display all columns :
{% for product in products %} {% for col in cols %} {{ col }}: {{ product.col }} {% endfor %} {% endfor %}
Obviously, this will result in error, because there is no "col" in product.
Is there any solution or alternative for this ?
-
Haozhe Xie almost 9 yearsNot working at all. Error message:
Fatal error: Call to undefined method stdClass::readAttribute()
. -
Yvan almost 9 yearsIf the error says
stdClass
, that clearly means that you didn't give a model object, as in Phalcon all objects inherit from Phalcon\Mvc\Model constructor. And the initial question clearly implies it:fetch all records
. -
Haozhe Xie almost 9 yearsI have inherit the model class from
Phalcon\Mvc\Model
. And I'm using Phalcon 2.0. -
Yvan almost 9 yearsI really doubt that: github.com/phalcon/cphalcon/blob/2.0.0/phalcon/mvc/… => the method exists, and you have «stdClass» in your error description, which means that you're dumping a default class, not a Phalcon object. Try a
{{ dump(product) }}
in volt, you'll see that's not a Phalcon object. -
Haozhe Xie almost 9 yearsYes, you're right. Because I get the object using
{% set i18nCategoryName = courseCategory['courseCategoryName'] | json_decode %}
. And I want to get the attribute{language}
(is a variable) of thei18nCategoryName
. So this method doesn't work for me. -
Yvan almost 9 yearsYou may use
defined
in this case, perhaps it would work as expected:{% if i18nCategoryName.property is defined %}
...{% endif %}