Integrating User Custom Fields

Views: 106

Once you become comfortable adding user custom fields anywhere that you need them, you will discover a whole new world of possibilities and be able to provide more value to each of your projects.

User Custom Fields

Including custom fields anywhere in your template that uses the 'User Object' programmatically can be accomplished using the following steps:

    1. Add the following line to the top of the php file you want to the custom field to display on:
      use Joomla\Component\Fields\Administrator\Helper\FieldsHelper;
    2. Depending on where the article object is being called (if in module or category page it would be inside a 'foreach' array, if in an article page, anywhere in the top php code would work):
      $jcFields = FieldsHelper::getFields(com_users.user', $user, true);
      foreach($jcFields as $jcfield)
      {
      $jcFields[$jcfield->name] = $jcfield;
      }
    3. Add the custom fields you wish to include after the code in Step 2:
      $mycustomfield = $jcFields['mycustomfield-alias']->rawvalue;

Breaking down the following line from above:
$jcFields = FieldsHelper::getFields('com_users.user', $user, true);

  1. 'com_users.user': This tells the code to look for custom fields related to the 'User Object'
  2. '$user': is the 'User Object' ("Specific User") that the custom fields are going to be pulled from
  3. 'true':indicates whether to display all the field data or (false) just the raw data - changing to false will shave a little time off the page load (especially if you are using a lot of custom fields)

Breaking down the following line from Step 3:
$mycustomfield = $jcFields['mycustomfield-alias']->rawvalue;

  1. '$mycustomfield': This can be whatever unique name you prefer to use to name your custom field variable (as long as it starts with '$')
  2. 'mycustomfield-alias': Alias name of the user custom field.
  3. 'rawvalue':indicates we are using the "raw" value of the custom field as opposed to the $mycustomfield = $jcFields['mycustomfield-alias']->value; That displays the default layout display of the custom field.

User Object Cheat Sheet

  • Top Of Most Pages - added at the top of the page
    $user = Factory::getApplication()->getIdentity();