Difference between revisions of "PHP Based Formatting"

From JReviews Documentation
Jump to: navigation, search
 
(25 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 +
<div class="successbox" style="width: 95%">
 +
 +
[https://www.jreviews.com/docs/developers/custom-field-php-formatting There's a new version of this article]
 +
 +
</div>
 +
 
PHP Based Formatting for Custom Fields adds an incredible amount of flexibility to what you can do with the output of custom fields. With some basic knowledge of php programming you can start creating conditionals in no time to modify the output of custom fields.
 
PHP Based Formatting for Custom Fields adds an incredible amount of flexibility to what you can do with the output of custom fields. With some basic knowledge of php programming you can start creating conditionals in no time to modify the output of custom fields.
  
 
__TOC__
 
__TOC__
 +
 +
To format the output of a custom field with php, go to the [[Fields Manager]], click on the field name and add your php code to the '''PHP Based Formatting''' setting under Advanced Options:
 +
 +
[[File:Php-based-formating.png]]
 +
  
 
== Available PHP Classes and Variables ==
 
== Available PHP Classes and Variables ==
  
 
{| class="wikitable" cellpadding="0" cellspacing="0"
 
{| class="wikitable" cellpadding="0" cellspacing="0"
 +
|-
 +
|'''PHP Classes'''
 
|-
 
|-
 
|$CustomFields || The JReviews CustomFields theme helper which lets you use the same methods described in [[How_to_customize_the_layout_of_custom_fields_in_Theme_files|How to customize the layout of custom fields in Theme_files]].
 
|$CustomFields || The JReviews CustomFields theme helper which lets you use the same methods described in [[How_to_customize_the_layout_of_custom_fields_in_Theme_files|How to customize the layout of custom fields in Theme_files]].
Line 15: Line 28:
 
|$Access || The JReviews Access class lets you quickly find out if a user has access to perform certain actions or determine if the user belongs to a specific user group.
 
|$Access || The JReviews Access class lets you quickly find out if a user has access to perform certain actions or determine if the user belongs to a specific user group.
 
|-
 
|-
 +
|'''Variables'''
 +
|-
 +
 
|$name || The custom field name.
 
|$name || The custom field name.
 
|-
 
|-
Line 47: Line 63:
  
 
<source lang="php">return false;</source>
 
<source lang="php">return false;</source>
 +
 +
=== Displaying the current listing's category link ===
 +
 +
To output the link using the category title:
 +
 +
<source lang="php">
 +
$Routes = new RoutesHelper;
 +
return $Routes->category($entry,$entry['Category']);
 +
</source>
 +
 +
To create your own link with a custom anchor text:
 +
 +
<source lang="php">
 +
$Routes = new RoutesHelper;
 +
$url = $Routes->category($entry, array('return_url'=>'true'));
 +
return sprintf('<a href="%s">Some text</a>',$url);
 +
</source>
 +
 +
=== Displaying the MyListings link for the current listing's owner ===
 +
 +
<source lang="php">
 +
$Routes = new RoutesHelper;
 +
return $Routes->myListings($entry['User']['name'], $entry['User']['user_id']);
 +
</source>
 +
 +
If you prefer to show the username instead, then replace 'name' with 'username'.
  
 
=== Displaying a message for guests and the real output to logged in users ===
 
=== Displaying a message for guests and the real output to logged in users ===
 +
 +
'''JReviews 3'''
  
 
<source lang="php">
 
<source lang="php">
if($Access->isGuest()) {
+
if ( $User->guest ) {
 
   return "You must be logged in to view this field";
 
   return "You must be logged in to view this field";
 
}
 
}
Line 62: Line 106:
  
 
<source lang="php">
 
<source lang="php">
if($User->id == 0) {
+
if( !$User->id ) {
 +
  return "You must be logged in to view this field";
 +
}
 +
else {
 +
  return $output;
 +
}
 +
</source>
 +
 
 +
'''JReviews 2'''
 +
 
 +
<source lang="php">
 +
if($Access->isGuest()) {
 
   return "You must be logged in to view this field";
 
   return "You must be logged in to view this field";
 
}
 
}
Line 75: Line 130:
  
 
<source lang="php">
 
<source lang="php">
$city = $CustomField->fieldValue('jr_city',$entry);
+
$city = $CustomFields->fieldValue('jr_city',$entry);
  
 
switch($city) {
 
switch($city) {
Line 108: Line 163:
 
</source>
 
</source>
  
 +
=== Display a field only if an option has been checked in another checkbox field ===
  
 +
This can be used to let listing owners decide whether they want to display a certain field even if the field is required to submit the listing. So lets assume you have some contact information fields like email, address, etc. You could create a single checkbox field with the options you want to let the user control and then for each field you would use a similar format as the one below and change the value of the option.
  
 +
<source lang="php">
 +
$checkboxes = $CustomFields->fieldValue('jr_checkbox',$entry);
 +
 +
if(in_array('email',$checkboxes)) {
 +
  return $output;
 +
}
 +
 +
return false;
 +
</source>
 +
 +
=== Display a field only if an option has been selected in another radio or select field ===
 +
 +
This is the same as the previous example, but using a radio or select list:
 +
 +
<source lang="php">
 +
$selected = $CustomFields->fieldValue('jr_radio',$entry);
 +
 +
if ( $selected == 'yes' ) {
 +
  return $output;
 +
}
 +
 +
return false;
 +
</source>
 +
 +
"yes" is the option value of the selected radio button or select list field.
 +
 +
=== Concatenating address fields while checking if they are filled out or not ===
 +
 +
In some cases you may have address fields that are left empty and you want to avoid having multiple commas together when joining the fields in a single banner custom field. You can use this approach to solve this:
 +
 +
<source lang="php">
 +
$out = array();
 +
$names = array('jr_addressline1', 'jr_addressline2', 'jr_addressline3', 'jr_town', 'jr_city', 'jr_county', 'jr_postcode');
 +
foreach($names AS $name) {
 +
  $out[] = $CustomFields->fieldValue($name, $entry);
 +
}
 +
$out = array_filter($out);
 +
$out = implode(', ', $out);
 +
if($out != '') {
 +
  return $out;
 +
}
 +
return false;
 +
</source>
 +
 +
=== Hiding the output of a field until a button is clicked ===
 +
 +
We use the listing id as part of the javascript code so that the elements have unique classes if used in list pages.
 +
 +
<source lang="php">
 +
$id = $entry['Listing']['listing_id'];
 +
$shown = '<span class="jrPhoneShow'.$id.' jrButton">Click to reveal info</span>';
 +
$hidden = '<span class="jrPhoneHidden'.$id.' jrHidden">'.$text.'</span>';
 +
$script = '
 +
<script>
 +
  (function($) {
 +
      $(".jrPhoneShow'.$id.'").on("click",function() {
 +
        $(this).hide();
 +
        $(".jrPhoneHidden'.$id.'").show();
 +
      });
 +
  })(jQuery);
 +
</script>'; 
 +
return $shown . $hidden . $script;
 +
</source>
 +
 +
The above example doesn't work if you display the fields in content loaded via ajax like the related listings widgets or the WidgetFactory. Below we have a simpler version of the code using the 'onclick' attribute that works in ajax loaded content.
 +
 +
<source lang="php">
 +
return '<span class="jrButton" data-value="'.$text.'" onclick="jQuery(this).html(jQuery(this).data(\'value\')).removeClass(\'jrButton\');">Click to reveal info</span>';
 +
</source>
 +
 +
=== Performing calculations with fields ===
 +
 +
If you have fields with numeric values and need to calculate a different value you can use a banner field to perform the calculations.
 +
 +
 +
==== Total sales based on price and volume ====
 +
 +
 +
<source lang="php">
 +
$price = $CustomFields->fieldValue('jr_price',$entry);
 +
$volume = $CustomFields->fieldValue('jr_volume',$entry);
 +
$total = $price * $volume;
 +
return $total;
 +
</source>
 +
 +
If one of the values is zero, you can display the default output of the banner instead:
 +
 +
<source lang="php">
 +
$price = $CustomFields->fieldValue('jr_price',$entry);
 +
$volume = $CustomFields->fieldValue('jr_volume',$entry);
 +
$total = $price * $volume;
 +
if($total > 0) {
 +
  return $total;
 +
}
 +
else {
 +
  return $output;
 +
}
 +
</source>
 +
 +
And if you would rather display the result of the calculation within the price field itself, instead of using a banner field you can do it this way:
 +
 +
<source lang="php">
 +
$price = $value; // This is the current value of the price field
 +
$volume = $CustomFields->fieldValue('jr_volume',$entry);
 +
$total = $price * $volume;
 +
return $total;
 +
</source>
 +
 +
 +
==== Current age using the birth date entered via a date custom field ====
 +
 +
 +
<source lang="php">
 +
$bday = new DateTime($text);
 +
$today = new DateTime();
 +
$diff = $today->diff($bday);
 +
return $diff->y;
 +
</source>
  
 
[[Category:JReviews]]
 
[[Category:JReviews]]
 
[[Category:Fields]]
 
[[Category:Fields]]

Latest revision as of 16:35, 29 July 2020

PHP Based Formatting for Custom Fields adds an incredible amount of flexibility to what you can do with the output of custom fields. With some basic knowledge of php programming you can start creating conditionals in no time to modify the output of custom fields.

To format the output of a custom field with php, go to the Fields Manager, click on the field name and add your php code to the PHP Based Formatting setting under Advanced Options:

Php-based-formating.png


Available PHP Classes and Variables

PHP Classes
$CustomFields The JReviews CustomFields theme helper which lets you use the same methods described in How to customize the layout of custom fields in Theme_files.
$User The Joomla User object contains information about the current logged in user.
$DB The Joomla Database object allows you to query the database.
$Access The JReviews Access class lets you quickly find out if a user has access to perform certain actions or determine if the user belongs to a specific user group.
Variables
$name The custom field name.
$entry The complete listing or review array depending on the location of the field.
$field The array for the current custom field.
$fields The array of all custom fields available for the entry.
$value A string or array with the current field values. Multiple option fields like checkboxes and multiple select will be arrays, while other fields will be strings. For fields without options (text, decimal, integer, etc.) the $value matches the $text variable below.
$text A string or array with the current field values. Multiple option fields like checkboxes and multiple select will be arrays, while other fields will be strings.
$image A string or array with the current field option image name if one was assigned.
$output An array with the current output for the field.

Examples

  • Don't include php tags in the code.
  • Always 'return' the output instead of using 'echo'.

Displaying the default output without changes

This is the most basic output. It doesn't change the default output of the field

return $output;

Hiding the field

return false;

Displaying the current listing's category link

To output the link using the category title:

$Routes = new RoutesHelper;
return $Routes->category($entry,$entry['Category']);

To create your own link with a custom anchor text:

$Routes = new RoutesHelper;
$url = $Routes->category($entry, array('return_url'=>'true'));
return sprintf('<a href="%s">Some text</a>',$url);

Displaying the MyListings link for the current listing's owner

$Routes = new RoutesHelper;
return $Routes->myListings($entry['User']['name'], $entry['User']['user_id']);

If you prefer to show the username instead, then replace 'name' with 'username'.

Displaying a message for guests and the real output to logged in users

JReviews 3

if ( $User->guest ) {
   return "You must be logged in to view this field";
}
else {
   return $output;
}

Another way to accomplish the same thing:

if(  !$User->id ) {
   return "You must be logged in to view this field";
}
else {
   return $output;
}

JReviews 2

if($Access->isGuest()) {
   return "You must be logged in to view this field";
}
else {
   return $output;
}

Display different images in banner field depending on selected value in select list

The following code goes in the PHP Based Formatting of the banner field.

$city = $CustomFields->fieldValue('jr_city',$entry);
 
switch($city) {
   case 'san-francisco':
      $banner = "sanfrancisco.jpg";
   break;
   case 'new-york':
      $banner = "newyork.jpg";
   break;
   default: // All other cities display the banner normally
       return $output;
   break;
}
 
$banner = '/media/banners' . $banner;
 
return "<img src=".$banner." />";

Display checkbox or multiple select field only if at least two options are checked

$count = is_array($output) ? count($output) : 1;
 
 
if($count > 1) {
   return $output;
}
else {
   return false;
}

Display a field only if an option has been checked in another checkbox field

This can be used to let listing owners decide whether they want to display a certain field even if the field is required to submit the listing. So lets assume you have some contact information fields like email, address, etc. You could create a single checkbox field with the options you want to let the user control and then for each field you would use a similar format as the one below and change the value of the option.

$checkboxes = $CustomFields->fieldValue('jr_checkbox',$entry);
 
if(in_array('email',$checkboxes)) {
   return $output;
}
 
return false;

Display a field only if an option has been selected in another radio or select field

This is the same as the previous example, but using a radio or select list:

$selected = $CustomFields->fieldValue('jr_radio',$entry);
 
if ( $selected == 'yes' ) {
   return $output;
}
 
return false;

"yes" is the option value of the selected radio button or select list field.

Concatenating address fields while checking if they are filled out or not

In some cases you may have address fields that are left empty and you want to avoid having multiple commas together when joining the fields in a single banner custom field. You can use this approach to solve this:

$out = array();
$names = array('jr_addressline1', 'jr_addressline2', 'jr_addressline3', 'jr_town', 'jr_city', 'jr_county', 'jr_postcode');
foreach($names AS $name) {
   $out[] = $CustomFields->fieldValue($name, $entry);
}
$out = array_filter($out);
$out = implode(', ', $out);
if($out != '') {
   return $out;
}
return false;

Hiding the output of a field until a button is clicked

We use the listing id as part of the javascript code so that the elements have unique classes if used in list pages.

$id = $entry['Listing']['listing_id'];
$shown = '<span class="jrPhoneShow'.$id.' jrButton">Click to reveal info</span>';
$hidden = '<span class="jrPhoneHidden'.$id.' jrHidden">'.$text.'</span>'; 
$script = '
<script>
   (function($) {
      $(".jrPhoneShow'.$id.'").on("click",function() {
         $(this).hide();
         $(".jrPhoneHidden'.$id.'").show();
      });
   })(jQuery);
</script>';  
return $shown . $hidden . $script;

The above example doesn't work if you display the fields in content loaded via ajax like the related listings widgets or the WidgetFactory. Below we have a simpler version of the code using the 'onclick' attribute that works in ajax loaded content.

return '<span class="jrButton" data-value="'.$text.'" onclick="jQuery(this).html(jQuery(this).data(\'value\')).removeClass(\'jrButton\');">Click to reveal info</span>';

Performing calculations with fields

If you have fields with numeric values and need to calculate a different value you can use a banner field to perform the calculations.


Total sales based on price and volume

$price = $CustomFields->fieldValue('jr_price',$entry);
$volume = $CustomFields->fieldValue('jr_volume',$entry);
$total = $price * $volume;
return $total;

If one of the values is zero, you can display the default output of the banner instead:

$price = $CustomFields->fieldValue('jr_price',$entry);
$volume = $CustomFields->fieldValue('jr_volume',$entry);
$total = $price * $volume;
if($total > 0) {
   return $total;
}
else {
   return $output;
}

And if you would rather display the result of the calculation within the price field itself, instead of using a banner field you can do it this way:

$price = $value; // This is the current value of the price field
$volume = $CustomFields->fieldValue('jr_volume',$entry);
$total = $price * $volume;
return $total;


Current age using the birth date entered via a date custom field

$bday = new DateTime($text);
$today = new DateTime();
$diff = $today->diff($bday);
return $diff->y;