Skip to content

Instantly share code, notes, and snippets.

@ChVuagniaux
Created December 19, 2016 08:40
Show Gist options
  • Save ChVuagniaux/ee455e02cf84336fb7e2692c097f0518 to your computer and use it in GitHub Desktop.
Save ChVuagniaux/ee455e02cf84336fb7e2692c097f0518 to your computer and use it in GitHub Desktop.
Joomla - K2 extrafield formating helper
<?php
class K2Helper
{
/**
* Convert K2 extra fields to an object
*
* Selectable extra fields ever return values inside an array
* same if only one value is selected
*
* @param string|array $itemExtraFields
*
* @return null|stdClass
*/
public static function getK2ExtraFields($itemExtraFields)
{
$itemExtraFieldsObject = new stdClass();
if (is_string($itemExtraFields))
{
$itemExtraFields = json_decode($itemExtraFields);
}
if (count($itemExtraFields) == 0)
{
return null;
}
if (!isset($itemExtraFields[0]->alias))
{
$db = \JFactory::getDbo();
$query =
$db->getQuery(true)
->select('id,value')
->from('#__k2_extra_fields');
$db->setQuery($query);
$extraFields = $db->loadAssocList('id');
}
foreach ($itemExtraFields as $itemExtraField)
{
$extraFieldValues = json_decode($extraFields[$itemExtraField->id]['value']);
if (!isset($itemExtraField->alias))
{
$itemExtraField->alias = json_decode($extraFields[$itemExtraField->id]['value'])[0]->alias;
}
// ignore unknown extra fields
if (empty($itemExtraField->alias))
{
continue;
}
// simple extra-field (without selectable values)
if (empty($extraFieldValues[0]->name))
{
$itemExtraFieldsObject->{$itemExtraField->alias} = $itemExtraField->value;
continue;
}
// ONLY for extra-fields with selectable values
if (!is_array($itemExtraField->value))
{
$itemExtraField->value = [$itemExtraField->value];
}
$values = [];
foreach ($itemExtraField->value as $refValue)
{
foreach ($extraFieldValues as $extraFieldValue)
{
if ($extraFieldValue->value == $refValue)
{
$values[] = $extraFieldValue->name;
break;
}
}
}
$itemExtraFieldsObject->{$itemExtraField->alias} = $values;
}
return $itemExtraFieldsObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment