0

You can use hook_entity_load to add fields to the user object like so:

function mymodule_entity_load($entities, $type)
{
    if ($type == 'user'  )
    {
       foreach($entities as $e) {
         $e->myField = 'hello';
       }
    }
}

That will allow me to do this in twig:

{{ user.myField }}

This is quite useful, but it would be great if I could do this:

{{ user.getActivity() }}

Or more specifically:

<h1>Members</h1>
<ul>
    {% for activity in user.getActivity()  %}
        <li>{{ activity.time }}</li>
    {% endfor %}
</ul>

Is there a way to add a "function" in this way?

  • Yes, twig can call object methods. See: stackoverflow.com/a/15277822/8507497 – CG Monroe Jul 17 at 20:52
  • Where is that activity info coming from? Why don't you simply add a normal field to the user entity? Why do you need it exactly that way in Twig? Wouldn't it be easier to simply hook_preprocess the user and add the info from there if you only need it in Twig? – leymannx Jul 17 at 20:56
  • 2
    But no, you can't add methods to an object/class at runtime – Clive Jul 17 at 21:04

Your Answer

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

Browse other questions tagged or ask your own question.