3

I have created some custom fields in my joomla article from backend now I want to fetch them in another component. What would be the code to achieve it?

  • Do you know how it is possible to retrieve Articles by FieldValues? – LiliwoL Jan 24 '18 at 12:21
5

You can use the following code to fetch custom field values by article id

<?php       
        JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php'); //load fields helper
        $customFieldnames = FieldsHelper::getFields('com_content.article', $article_id, true); // get custom field names by article id
        $customFieldIds = array_map(create_function('$o', 'return $o->id;'), $customFieldnames); //get custom field Ids by custom field names
        $model = JModelLegacy::getInstance('Field', 'FieldsModel', array('ignore_request' => true)); //load fields model
        $customFieldValues = $model->getFieldValues($customFieldIds , $item->content_item_id); //Fetch values for custom field Ids
?>

Hope it will help you.

| improve this answer | |
  • Do you know how it is possible to retrieve Articles by FieldValues? – LiliwoL Jan 24 '18 at 12:21
  • But you have not defined $article_id (and a spelling mistake). How do you find the article ID? – Eoin Jul 6 '18 at 23:07
  • Ok here is how you get the active article ID ` $app = JFactory::getApplication(); // Access the Application Object $menu = $app->getMenu(); // Load the JMenuSite Object $active = $menu->getActive(); // Load the Active Menu Item as an stdClass Object $article_id = $active->id;` – Eoin Jul 6 '18 at 23:25
  • create_function is depreciated in PHP 7.2. What would be the best way to fetch without it? – YellowWebMonkey Mar 9 at 15:11
2

This function will allow display of JCFields anywhere in any extension desired, including templates.

The first parameter is the only requirement and will dump the JCF data, based on the item ID inserted. The default context is com_content.article and that can be set to any context where JCF data is held.

The second param is the field ID. If set, the data for that single custom field will be retrieved.

The third param will allow calls to specific JCF database fields. This is ideal for minimal data retrieval. It is triggered only when a single $srcId value is detected. I considered using a boolean method to allow choosing when needed, but I didn't need it for the project. It can be modified as desired.

The last param will set the context value such as com_users.users

function getJCFields($srcId, $fieldId=null, $dbfields=null, $context=null)
{
    if( is_null($context) )
        $context = 'com_content.article';
    
    if( is_array($srcId) || is_object($srcId) ) {
        JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR.'/components/com_fields/helpers/fields.php');
        $jfields = FieldsHelper::getFields($context, $srcId, true);
    }
    else
    if( is_int($srcId) ) 
    {
        if( is_null($dbfields) )
            $dbfields = 'id,label,value,item_id';
        
        $db = JFactory::getDbo();
        $db->setQuery('
        SELECT '.$dbfields.'
        FROM #__fields 
        LEFT JOIN #__fields_values ON #__fields.id = #__fields_values.field_id
        WHERE context = "'.$context.'" 
        AND #__fields_values.item_id = '.$srcId.'
        AND #__fields.state = 1
        ');
        
        $jfields = $db->loadObjectList();
    }
    
    $fieldval=[];
    foreach($jfields as $val)
    {
        $fieldval[$val->id] = (object)['label'=>$val->label,'value'=>$val->value];
    }
    
    $fval = $fieldval;
    if( !is_null($fieldId) ) {
        $fval = $fieldval[$fieldId];
    }

    return $fval;
}

Usage Methods

Set a variable with the source item and category ID as an associative array

$srcid = ['id'=>24, 'catid'=>5];    

Get field label

getJCFields($srcid, 9)->label;

Get field value

getJCFields($srcid, 9)->value;

Note: each output instance should be cased in a !empty() condition

Of course the conditional check can be written into the function for better completeness in the process.

Get creative with an array of fields

$fields = [2,3,4,5,6,8];

$cell=[];
foreach($fields as $fid) 
{
    $lbl = getJCFields($srcid, $fid)->label;
    $val = getJCFields($srcid, $fid)->value;
    if( !empty($val) ) {
        $cell[] = '<div class="tr"><div class="cell lbl">'.$lbl.'</div><div class="cell val">'.$val.'</div></div>';
    }
}

$fieldtbl = '
<div class="tbl chart">
    '.implode('', $cell).'
</div>
';

Other use

If you just want to get the JCF array for an item, then use within your special function, just use only the item ID for a minimal DB query for specific rows.

Note the ID must be an integer so it must not be enclosed in quotes

From com_content

getJCFields(293);

From com_users

Note: the $dbfields param can use aliases

getJCFields(16, null, 'id,value,label,item_id AS uid', 'com_users.user');

Output array

Array
(
    [0] => stdClass Object
        (
            [id] => 2
            [label] => Address
            [value] => 400 W Church St #200, Orlando, FL 32801
            [item_id] => 293
        )

    [1] => stdClass Object
        (
            [id] => 4
            [label] => Phone
            [value] => 407-440-7900
            [item_id] => 293
        )

)

end


Update: Alternative to get data from elements not included in the default return object which output only label and value.

getJCFields($srcid)[9]->author_name;
getJCFields($srcid)[9]->params;
getJCFields($srcid)[9]->description;

| improve this answer | |
  • A code review for you (and researchers) to consider: 3v4l.org/S3NaQ . If you like any parts of it, I welcome you to edit them into your answer. If you would like me to explain anything further, just ask. I noticed that item_id was not used in $fieldval[$val->id] = (object)['label'=>$val->label,'value'=>$val->value]; despite being declared in the fallback SELECT values of the query. – mickmackusa Aug 22 at 1:55
  • @mickmackusa I didn't need that item_id index for the project, solely because it only called for the label and value. As stated in the post, anyone can add or remove what ever is desired to serve their purpose. It is merely base to build on. – Nadal Aug 22 at 4:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.