XF 2.0 Get a custom field value from $user inside a template

abdfahim

Well-known member
Is there a better way of doing this? Right now I am doing like (in message_macros template)
Code:
<xf:if is = "{$user.Profile.custom_fields.getFormattedValue('customA')|raw} != ''">
    <span class="classA"></span>
<xf:elseif is = "{$user.Profile.custom_fields.getFormattedValue('customB')|raw} != ''" />
    <span class="classB"></span>
<xf:elseif is = "{$user.Profile.custom_fields.getFormattedValue('customC')|raw} != ''" />
    <span class="classC"></span>
<xf:elseif is = "{$user.custom_fields.getFormattedValue('customD')|raw} != ''" />
    <span class="classD"></span>
</xf:if>
 
Last edited:
With above code, I am getting following errors for some users, I guess whoever hasn't set the value for the custom fields

Code:
Template public:message_macros: Accessed unknown getter 'custom_fields' on XF:User[1426] (src\XF\Mvc\Entity\Entity.php:175)
Template public:message_macros: Cannot call method getFormattedValue on a non-object (NULL) (src\XF\Template\Templater.php:907)
 
I solved the issue as below. Is it the right way, or there is a better way? Any advice is highly appreciated.

message_macros template
Code:
<xf:if is = "{$user.Profile.custom_fields.customA} AND {$user.Profile.custom_fields.getFormattedValue('customA')|raw} != ''">
    <span class="classA"></span>
<xf:elseif is = "{$user.Profile.custom_fields.customB} AND {$user.Profile.custom_fields.getFormattedValue('customB')|raw} != ''" />
    <span class="classB"></span>
<xf:elseif is = "{$user.Profile.custom_fields.customC} AND {$user.Profile.custom_fields.getFormattedValue('customC')|raw} != ''" />
    <span class="classC"></span>
<xf:elseif is = "{$user.Profile.custom_fields.customD} AND {$user.custom_fields.getFormattedValue('customD')|raw} != ''" />
    <span class="classD"></span>
</xf:if>
 
The issue is your last condition: $user.custom_fields (instead of the correct value used in all of the others)

I don't know what your fields are, though the "simple" value you get from the condition you added is probably sufficient.
 
Oh, thanks for the correction and the idea of simple value. So, I end up like
Code:
<xf:if is = "{$user.Profile.custom_fields.customA} AND {$user.Profile.custom_fields.customA} != ''">
    <span class="classA"></span>
<xf:elseif is = "{$user.Profile.custom_fields.customB} AND {$user.Profile.custom_fields.customB} != ''" />
    <span class="classB"></span>
<xf:elseif is = "{$user.Profile.custom_fields.customC} AND {$user.Profile.custom_fields.customC} != ''" />
    <span class="classC"></span>
<xf:elseif is = "{$user.Profile.custom_fields.customD} AND {$user.Profile.custom_fields.customD} != ''" />
    <span class="classD"></span>
</xf:if>
 
Hi,

Is it possible to get the title of a custom field from its ID? Something like titleOf($user.Profile.custom_fields.customA) or {$user.Profile.custom_fields.customA.title}.
 
Back
Top Bottom