XF 2.0 How to get custom field value in PHP when it's from a set of choices

XFConvert

Member
Licensed customer
Have my own PHP script to authenticate an XF2 user and trying to get the custom profile fields, like "country". That profile field is from a set of choices. Here is how far I've gotten:

PHP:
// bootstrap framework
$dir = __DIR__;
require($dir . '/src/XF.php');

XF::start($dir);

$app = \XF::setupApp('XF\App');

$username = "someuser";
$password = "somepassword"

$ip = $app->request->getIp();
$loginService = $app->service('XF:User\Login', $username, $ip);

$user = $loginService->validate($password, $error);

echo $user->Profile->custom_fields->country;

The output of $user->Profile->custom_fields->country is something like:

"united_states_2"

which is apparently some kind of reference to the actual string in the set of choices for that custom profile field.

Exactly how do I get the actual string value (which in this case should be "United States")?

Thanks in advance for any help!
 
Code:
$entityManager = \XF::app()->em();

/** @var \XF\Mvc\Entity\Finder $fieldFinder */
$fieldFinder = $em->getFinder('XF:UserField');

/* Get all user fields */
/** @var \XF\Mvc\Entity\ArrayCollection $allUserFields */
$allUserFields = $finder->fetch();

/* Get a set of user fields */
/** @var \XF\Mvc\Entity\ArrayCollection $userFields */
$userFields = $finder->where('field_id', '=', ['set', 'of', 'field', 'ids'])->fetch();

/* Get a single user field */
/** @var \XF\Entity\UserField $userField */
$userField = $finder->where('field_id', '=', 'country')->fetchOne();

After that match them against your user values to get the display values.
 
Thank you very much katsulynx, that was a huge help. I had to play around with it a bit but I got it working.

Now a related question if I may.

What would the template syntax be to do the same thing -- but in a thread post? Basically I want to add a custom field like "country" near the username on each post in a thread. (And again, the value for that custom field is from a set of choices like what I explained above.)
 
Back
Top Bottom