1

I have two custom fields in my article for longitude and latitude. I'm then trying to build a module to get these two fields from the current article displayed and show in the module.

I have the following but it's not working:

<?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) {
        var_dump($field->value);
    }
?>

It's not even showing when using var_dump

Ideally, I'd like to create the variables in the foreach and assign $latitude and $longitude a value (from the article custom field)

1
  • I have several answers to pivot questions (some that relate to #__fields_values). If they don't help, please create a db-fiddle with some sample rows and I'll spin up a query for you. Out of curiosity, does $item->id contain the expected value when you test your script? Commented Nov 16, 2021 at 10:47

1 Answer 1

1

Assuming this is for Joomla 3, you can use the following:

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;

\JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
BaseDatabaseModel::addIncludePath(JPATH_SITE . '/components/com_content/models', 'ContentModel');

$model = BaseDatabaseModel::getInstance('Article', 'ContentModel', ['ignore_request' => true]);
$model->setState('params', Factory::getApplication()->getParams());
$fields = FieldsHelper::getFields(
    'com_content.article',
    $model->getItem(Factory::getApplication()->input->get('id')),
    true
);

$array = [];

foreach($fields as $field)
{
    $array[$field->name] = $field->value;
}

This will get the current ID, then obtain the fields associated with said ID. It will then create a new array with the name of the field as the key.

If you var_dump the array, you will see the following response:

Array
(
    [longitude] => 184
    [latitude] => 185
)

You can then do whatever you like with the $array of fields.

Note, the above code is very basic. You may want to add in some sanity checks to prevent any potential PHP errors. E.g checking if ID actually exists, etc.

3
  • extract()? Why do you need separate variables? I don't endorse the use of "variable variables" -- they usually indicate that an opportunity to use arrays has been missed. Commented Dec 8, 2021 at 11:24
  • Thanks! This is showing the array, but how can I then set a variable based on the array strings? Commented Dec 8, 2021 at 11:56
  • Have some comments been removed? I don't know who mick ask talking to regarding extract()...
    – Lodder
    Commented Dec 8, 2021 at 13:53

Your Answer

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

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