0
<?php 
  // Turn fields from array numbers into field names.  I usually stick this in the head somewhere.
  foreach($this->item->jcfields as $jcfield){
    $this->item->field[$jcfield->name] = $jcfield;
  }
?>

// Call the field by the name.  With error checking if it is empty.  
<?php
    echo "Value: " . $this->item->field['price']->value;
?>

So here I have a field called "price" that is being called by the name.

But say I decide I want to put it in a function instead. I tried but I'm getting a using $this in non object context. Here's what I tried:

function callFieldByName($fieldName){
    echo "Value: " . $this->item->field[$fieldName]->value;
    }

callFieldByName('price');

Seems like a pretty noob question. Thanks for your help in advance.

1

I presume you're in a template override of com_content. In which case your $this will point to an instance of a view class, eg. ContentViewArticle or something.

PHP does allow you to declare functions at runtime within objects but $this won't be in scope so you have to pass in a handle of the object. So you can do the following:

foreach($this->item->jcfields as $jcfield){
    $this->item->field[$jcfield->name] = $jcfield;
}    

function showField($obj,$name){
    echo (!empty($obj->item->field[$name]->value)) ? "Value: " . $obj->item->field[$name]->value : "";
}

showField($this,'price');

Which really seems like it isn't worth it. It's probably easier to just do the work in the foreach loop to prepare for layout. eg.

$f = [];
foreach($this->item->jcfields as $jcfield){
    $f[$jcfield->name] = (!empty($jcfield->value)) ? "<br>Value: " . $jcfield->value : "";
}
| improve this answer | |

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.