1

For some reason i need tu use articles custom fields in index.php file template, i try this code without success :

This after defined('_JEXEC') or die('Restricted access');
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
JModelLegacy::addIncludePath(JPATH_SITE.'/components/com_content/models', 'ContentModel');

$id = JFactory::getApplication()->input->get('id');

$model =& JModelLegacy::getInstance('Article', 'ContentModel', array('ignore_request'=>true));
$appParams = JFactory::getApplication()->getParams();
$model->setState('params', $appParams);
$item =& $model->getItem($id);
$jcFields = FieldsHelper::getFields('com_content.article',  $item, True);

<?php if (!empty(($this->item->jcfields[5]->value))) {
   echo " background";
} ?>
2
  • I ran your code inside my template's index.php and it worked ok. $jcFields got the custom fields data which I'd set up on my article. I'm not sure why you're subsequently referencing $this->item->jcfields - did you explicitly set that up? Did you trying doing var_dump($jcFields) after you set it? (note that you have a capital F in jcFields). Apr 11 '20 at 10:46
  • OK thanks i need to see that.
    – Laurent
    Apr 11 '20 at 13:06
0

I debug your code and your $jcFields = FieldsHelper::getFields('com_content.article', $item, True); is an empty array.

however, your $item =& $model->getItem($id) shows all the items of the article so the problem lies in $jcFields = FieldsHelper::getFields('com_content.article', $item, True); but i don't know exactly why. I have tried several solutions but no success. Perhaps we could wait for someone with more experience to give us a better solution.

16
  • 1
    Thanks but it is articles custom fields and no template fields.
    – Laurent
    Apr 10 '20 at 16:02
  • Oh that's tricky...let me try to find a solution. Apr 10 '20 at 16:03
  • Does it show any error? Apr 10 '20 at 16:05
  • 1
    Nothing, thanks.
    – Laurent
    Apr 10 '20 at 16:07
  • Your last edited code create a 404 error.
    – Laurent
    Apr 10 '20 at 16:14
0

For each article the fields values can vary depending on the inputs you gave and just $jcfield data is enough for you to get the desired custom field. The data you receive will be in array format based on number of custom fields you have. Suppose you have several custom fields and you want to access data of a particular custom field to be used in a template then you iterate all the likely fields and get data according to the id:

foreach($jcFields as $field){
    if($field->id == 5){
        echo $field->value;
        }
}

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.