1

I am using this code inside a module override that render articles, to show the custom fields:

<?php
    $id=$item->id;
    $db = JFactory::getDbo();
    $query = 'select * from #__fields_values where item_id = "'.$id.'"';
    $db->setQuery($query);
    $fields = $db->loadObjectList();

    foreach ($fields as $field) {
        if ($field->field_id == 4) { // 4 - id of your custom field
        echo $field->value;
        }
    }
    ?>

It works fine and renders the value of the field, but I want to display also the field label. Any help?

Thank you

1 Answer 1

3

The label is in the 'fields' table so you could pull them with the values in a single query by using a join, eg.

$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('a.value,b.label,b.id');
$query->from($db->qn('#__fields_values','a'));
$query->join('INNER', $db->qn('#__fields', 'b') . ' ON ' . $db->qn('a.field_id') . ' = ' . $db->qn('b.id'));
$query->where($db->qn('a.item_id') . ' = ' . $db->q($item->id));
$query->where($db->qn('b.context') . ' = ' . $db->q('com_content.article'));
$db->setQuery($query);
$fields = $db->loadObjectList('b.id'); // add the field id as the key

// For testing to see the whole array
echo '<pre>' . print_r($fields,1) . '</pre>';

// To show only specific fields, eg for field id 4
echo '<p>' . $fields[4]->label . ': ' . $fields[4]->value . '</p>';

// to show all the fields - warning they wont be in the order set in the fields interface
foreach ($fields as $field_id => $field) {
    echo '<p class="fid-' . $field_id . '">' . $field->label . ': ' . $field->value . '</p>';
}
6
  • Yes, it worked, just a small correction on the last line (please do it above) instead of <p> it is '<p>'. Can I show only specific custom fields? how? Thank you anyway.
    – geoplous
    Nov 11, 2018 at 6:35
  • more detail added to answer Nov 11, 2018 at 22:29
  • Sorry but it shows me only the last Custom Field ( with the last ID number) on either cases ("To show only specific fields" or to "show all the fields")
    – geoplous
    Nov 12, 2018 at 9:12
  • Are you sure there are additional field values set for the article at which you are looking? Nov 12, 2018 at 22:17
  • 100% sure, I used the 1st code that I have in my question and is working. Your 1st version "foreach ($fields as $field) { echo '</p>' . $field->label . ': ' . $field->value . '</p>'; } is also working. But it returns all CF from all CF Groups
    – geoplous
    Nov 13, 2018 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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