Inherit listing relations in reviews
- Thread started
- Last updated
What you’ll achieve
Show recent business reviews on their related city, state, country, and area listings.
My site
Show the latest reviews of local businesses on their city and state listing pages. A guest reviews a hotel in Chicago. That review also appears under Latest reviews on the Chicago and Illinois listings, alongside reviews of other businesses in those locations.
Prepare the relation fields
Create the business and location listings
This example uses three kinds of listings. Hotels belong to a business listing type. Cities and states have their own location listing types. Chicago and Illinois must each exist as a JReviews listing with its own detail page.
For the example below, assume these listings already exist:
| Listing | Listing type | Example listing ID |
|---|---|---|
| Lakefront Hotel | Hotel | 101 |
| Chicago | City | 20 |
| Illinois | State | 30 |
Use your own listing IDs. The numbers above only explain what the customization saves.
Add a Related Listing field to hotel listings
Create a listing custom field with the name jr_parents, the label Locations, and the type Related Listing. Assign its field group to the Hotel listing type so the field appears when someone adds or edits a hotel.
Configure the field's suggestion filters to include your City and State listing types. Allow more than one selection. Leave the maximum-selection setting blank for this example.
Edit Lakefront Hotel. In Locations, search for and select both Chicago and Illinois, then save the hotel. These selections refer to existing listings. You do not create predefined field options named Chicago and Illinois or enter those names as text values.
The field displays the selected listing titles. Its saved values are their listing IDs, 20 and 30 in this example. Select every location that should display the hotel's reviews. Selecting Chicago alone does not automatically include Illinois.
Add a Related Listing field to hotel reviews
Create a review custom field with the name jr_ascentparents, the label Related places and business, and the type Related Listing. Assign its review field group to the Hotel listing type so the field is available in hotel reviews.
Configure its suggestion filters to include the Hotel, City, and State listing types. This field must accept both the reviewed business and its locations. Leave the maximum-selection setting blank.
Keep this review field active in the review form, optional, writable by reviewers, and without field dependencies. Reviewers must also have permission to read the hotel's Locations field. If you use PaidListings, include the fields in the applicable plans.
The reviewer can leave Related places and business empty. The customization fills it when the review is saved and replaces any manual selections in that field.
Follow the values from the hotel to its review
After someone reviews Lakefront Hotel, the fields contain:
| Record and field | Selected listings | Saved listing IDs |
|---|---|---|
Hotel's jr_parents |
Chicago, Illinois | 20, 30 |
Review's jr_ascentparents |
Chicago, Illinois, Lakefront Hotel | 20, 30, 101 |
The code copies the hotel's selected location IDs and adds the hotel's own ID. Later in this guide, you configure a reviews display on each location listing. On Chicago, that display finds reviews whose jr_ascentparents contains Chicago's ID, 20. On Illinois, it looks for 30, so the same hotel review can appear on both pages.
The code copies the locations selected on the hotel. It does not follow additional relationships stored on Chicago or Illinois. Only select locations whose relationship to the business may be visible to people who can read the review field.
Keep the customization in your JReviews overrides. Start a new PHP file with <?php followed by defined('MVC_FRAMEWORK') or die;. In an existing file, add the callback without repeating the opening tag or guard. If a snippet includes those lines, keep each only once.
JReviews 6 Early Access
In Configuration > Early Access Settings, enable Listing Detail Page for the review form. To collect a review with a new listing, also enable Listing Form and configure the listing type to show an initial review.
Add the save action override
Create the following file inside your overrides folder:
Use templates/jreviews_overrides/app/Actions/StoreListingCommentAction.php.
Use jreviews_overrides/app/Actions/StoreListingCommentAction.php.
This action reads the saved listing when the review is ready to save. It also handles the first review submitted with a new listing, after that listing receives its ID.
<?php
namespace JReviewsOverrides\App\Actions;
defined('MVC_FRAMEWORK') or die;
use FWD\Illuminate\Http\Request;
use FWD\Illuminate\Support\Facades\Validator;
use JReviews\App\Contracts\Models\ListingModelContract;
use JReviews\App\Enums\CommentModerationIntentEnum;
use JReviews\App\Models\Comment;
use JReviews\App\Models\Field;
use JReviews\App\Models\User;
class StoreListingCommentAction extends \JReviews\App\Actions\StoreListingCommentAction
{
public static function destination(ListingModelContract $listing, User $user): ?Field
{
$source = $listing->getField('jr_parents');
$fields = $listing->listing_type->getCommentFormFields();
$destination = $fields->firstWhere('name', 'jr_ascentparents');
if (!$source || !$source->isRelatedListingField() || !$destination || !$destination->isRelatedListingField()
|| $user->cannot('read', $source) || $user->cannot('write', $destination)
|| !$destination->isActiveInForm($fields, new Request([]))) {
return null;
}
return $destination;
}
public static function ids(mixed $values, int $listingId = 0): array
{
$ids = array_filter(array_map('intval', (array) $values), fn ($id) => $id > 0);
if ($listingId > 0) {
$ids[] = $listingId;
}
return array_values(array_unique($ids));
}
public function handleWithModerationIntent(User $user, Comment $comment, array $data, CommentModerationIntentEnum $intent): Comment
{
$listing = $comment->listing;
if ($this->request->inFrontend() && $listing->exists && ($field = self::destination($listing, $user))) {
$listing->unsetRelation('field_data');
$data['fields']['jr_ascentparents'] = self::ids($listing->getFieldValue('jr_parents', []), (int) $listing->id);
$request = new Request($data);
$validator = Validator::make($data, []);
$field->manager()->request($request)->updating((bool) $comment->id)->setFormNamespace('fields')->addValidation($validator);
if ($maximum = (int) $field->params->max_options) {
$validator->addRules(['fields.jr_ascentparents' => ['array', 'max:'.$maximum]]);
}
$validator->validate();
}
return parent::handleWithModerationIntent($user, $comment, $data, $intent);
}
}
Register the override
Create or update classmap.php at your overrides root:
Use templates/jreviews_overrides/classmap.php.
Use jreviews_overrides/classmap.php.
A new file contains:
<?php
defined('MVC_FRAMEWORK') or die;
return [
JReviews\App\Actions\StoreListingCommentAction::class => JReviewsOverrides\App\Actions\StoreListingCommentAction::class,
];
If the file already returns an array, add this entry to that array. Keep existing mappings. If the same action already has an override, combine the behavior in that class and keep one mapping for the action.
Replace both field names consistently when your site uses different names. The override replaces manual selections in the destination field. An empty source still adds the reviewed listing itself. A later frontend review edit copies the listing's current saved relations. Control-panel saves keep their existing behavior.
JReviews first checks the ordinary review fields and ratings. The override then checks the copied selections, including their total against any maximum-selection limit, before saving. It does not check that every copied location ID still exists, is published, or has an allowed listing type. Keep valid, accessible location listings selected in the hotel's Locations field.
If you later set a maximum that is too small, JReviews rejects the review. During a combined submission, the listing has already been saved. Correct the limit, open that listing, and submit its review from the detail page.
JReviews 5 and v6 Legacy
Fill the review's Related places and business field with the hotel and its selected locations. The code replaces any selections the reviewer entered in that field.
Add the code to your overrides
Joomla. Use templates/jreviews_overrides/filters/filter_functions.php.
WordPress. Use jreviews_overrides/filters/filter_functions.php.
Prepare the listing and review relation fields
Copy all three callbacks below. Together they handle a review submitted on an existing hotel and an initial review submitted with a new hotel. The review field can start empty. For a new hotel, the code waits until the hotel has an ID before filling the review field.
The example reads listing relations from jr_parents in the jreviews_content table with your CMS database prefix. It writes those IDs, plus the ID of the listing being reviewed, to the review relation field jr_ascentparents.
Removing the review field from the form prevents its inherited values from being saved. The hook does not grant permission to submit reviews or edit fields.
Copy the relations for separate and initial reviews
Leave the review relation field's maximum-selection setting blank. Keep the field optional, active, writable by reviewers, and without field or field-group dependencies. The callbacks add the final relations after the listing ID is available.
Add the callbacks marked with +. Keep the database table names as shown; JReviews supplies your site's table prefix automatically.
- If
filter_functions.phpalready exists, add the marked lines at the end of the file. The copy button copies only those lines. - If you are creating
filter_functions.php, type the two dimmed lines first, then add the marked lines below them.
<?php
defined('MVC_FRAMEWORK') or die;
$inherit_listing_review_relations = function($request, $params)
{
$listing_id = (int) ($request['data']['Review']['pid'] ?? 0);
if ($listing_id < 1) {
return $request;
}
$source = FWDDB::table('jreviews_fields')
->where('name', 'jr_parents')
->where('location', 'content')
->where('published', 1)
->first(['name', 'access_view']);
if (!$source || !S2Object::make('perm')->__('field')->setField(['Field' => (array) $source])->canRead()) {
return $request;
}
$content = FWDDB::table('jreviews_content')
->where('contentid', $listing_id)
->first(['jr_parents']);
if (!$content) {
return $request;
}
$parents = $content->jr_parents;
$parent_ids = preg_split('/\*+/', trim((string) $parents, '*'), -1, PREG_SPLIT_NO_EMPTY);
$parent_ids = array_filter(array_map('intval', $parent_ids), function($id) {
return $id > 0;
});
$parent_ids[] = $listing_id;
$request['data']['Field']['Review']['jr_ascentparents'] = array_values(array_unique($parent_ids));
return $request;
};
Clickfwd\Hook\Filter::add('before_filter_request_reviews__save', $inherit_listing_review_relations);
Clickfwd\Hook\Filter::add('before_filter_request_listings__save', function ($request, $params) {
$request['data']['Field']['Review']['jr_ascentparents'] = $request['data']['Field']['Review']['jr_ascentparents'] ?? [];
return $request;
});
Clickfwd\Hook\Filter::add('review_save_pre', function ($data, $params) use ($inherit_listing_review_relations) {
$validationData = $data;
$validationData['Field']['Review']['jr_ascentparents'] = [];
$fields = ClassRegistry::getClass('FieldModel')->validate($validationData, 'review');
if (empty($fields['jr_ascentparents']['valid']) || $fields['jr_ascentparents']['type'] !== 'relatedlisting') {
return $data;
}
$request = $inherit_listing_review_relations(['data' => $data], $params);
return $request['data'];
});
Replace jr_parents and jr_ascentparents consistently with your field names. The first callback handles a review submitted separately. The listing callback keeps an empty review relation in a new listing submission, and the final review callback fills it after the listing receives an ID.
The code copies the hotel's selected locations, adds the hotel itself, and removes duplicates. It replaces the reviewer's manual selections. An empty Locations field adds only the hotel. If that field is missing, unpublished, or unreadable to the reviewer, the code leaves the submitted review field unchanged.
After JReviews checks the ordinary review, the final callback checks that Related places and business is still an active Related Listing field that the reviewer may edit. A denied or inactive field stays unchanged. Keep the field settings stated above. The code does not check each copied location against publication, permissions, or allowed listing types, so maintain valid, accessible locations on the hotel.
Show the inherited reviews on a city or other location
Suppose a hotel lists Chicago and Illinois in jr_parents. After a visitor reviews the hotel, jr_ascentparents contains Chicago, Illinois, and the hotel's own ID. Configure a related-reviews display on the Chicago and Illinois listings to find reviews containing their location ID.
Configure the display on the geographic listing type, such as City. Choose the business listing types in its reviews filter. Those are the listing types being reviewed, such as Hotel or Restaurant.
Configure Related Comments for the geographic listing type
Enable Listing Detail Page in Early Access. Open the geographic listing type's Related Comments widget settings and configure the widget:
- Enable Published and give the widget a title such as Latest reviews in this city.
- Set Find Reviews Where to The review listing type matches the selected listing types.
- Set Listing Types Filter to the business listing types whose reviews you want to show.
- Set Reviews Ordering to Most Recent and choose the result count.
- Leave JSON Custom Query empty for this example.
Match the location ID in inherited relations
Create the override class below. The example targets the first Related Comments widget on geographic listing type 42.
Use templates/jreviews_overrides/app/View/Components/Listing/RelatedComments.php.
Use jreviews_overrides/app/View/Components/Listing/RelatedComments.php.
<?php
namespace JReviewsOverrides\App\View\Components\Listing;
defined('MVC_FRAMEWORK') or die;
use FWD\Illuminate\Database\Eloquent\Builder;
class RelatedComments extends \JReviews\App\View\Components\Listing\RelatedComments
{
protected function applyCustomQueryAndOrdering(Builder $query, object $widget): void
{
$locationWidgets = [42 => 0];
$typeId = (int) $this->listing->listing_type_id;
if (isset($locationWidgets[$typeId]) && (int) $this->widgetId === $locationWidgets[$typeId]) {
$pattern = '%*'.(int) $this->listing->id.'*%';
$query->whereHas('field_data', function (Builder $fields) use ($pattern): void {
$fields->where('jr_ascentparents', 'LIKE', $pattern);
});
}
parent::applyCustomQueryAndOrdering($query, $widget);
}
}
Replace 42 in $locationWidgets with the geographic listing type's ID. The widget index starts at zero, so 0 is its first Related Comments widget. Change that value if your geographic display is another widget. To display reviews on separate City, State, and Country listing types, add an entry for each type and its widget index.
Change jr_ascentparents if your review field has a different name. The complete ID is matched between asterisks, so location 7 does not match relation 17. The widget keeps the normal publication and listing-type filters, excludes reviews of the geographic listing itself, and keeps the selected ordering and result count.
Add the class mapping to the same root classmap.php used for the save action. The complete array for both overrides is:
<?php
defined('MVC_FRAMEWORK') or die;
return [
JReviews\App\Actions\StoreListingCommentAction::class => JReviewsOverrides\App\Actions\StoreListingCommentAction::class,
JReviews\App\View\Components\Listing\RelatedComments::class => JReviewsOverrides\App\View\Components\Listing\RelatedComments::class,
];
Keep other existing mappings. If either original class already has an override, combine the behavior and keep one mapping per original class.
Configure Related Reviews for the geographic listing type
Open the geographic listing type's Related Reviews widget settings. Enable the widget and give it a title such as Latest reviews in this city.
Set Find Reviews Where to The review listing type matches the selected listing types. In Listing Types Filter, select the business listing types whose reviews should appear. Set Reviews Ordering to Most Recent and choose the result count.
Enter this in Custom Where:
ReviewField.jr_ascentparents LIKE '%*{listing_id}*%'
Change jr_ascentparents if your review field has a different name. On a listing detail page, {listing_id} becomes the geographic listing's ID. ReviewField reads the review's saved custom fields. Matching the complete asterisk-delimited ID prevents location 7 from matching relation 17.
Apply these widget settings to every geographic listing type where you want the review display, such as City, State, and Country. Keep your normal category navigation and review permissions.
Saving relations does not rewrite reviews that already exist. Edit and save an older review to copy the listing's current relations, then check its geographic displays.
Check saved review relations
Create a listing with an initial review and an empty review relation field. Save and reopen both. Confirm that the review contains the new listing ID and all saved parent locations. Then submit a separate review with an empty destination field. Save and reopen the review. Confirm it contains the reviewed listing and its source relations without duplicate IDs. Repeat with an empty source field and an edited review. Try a reviewer who cannot write the destination field and confirm the denied field remains unchanged.
Check the geographic result
Open the Chicago listing directly and confirm that its latest-reviews display contains the hotel review. Open Illinois and confirm that the same review appears there. Open an unrelated city and confirm that the review is absent. Include location IDs where one is part of another, such as 7 and 17.
Add another matching published review and check newest-first order and the result limit. Confirm that unpublished reviews and reviews of unpublished businesses stay out of the display. Test a review submitted with a new listing, a later separate review, and an edited review. Repeat as a logged-out visitor and with each relevant review permission group.