JReviews logo
Guides My site
← All guides Community guide

Choose listing photos in a repeatable FormBuilder field

A
Contributors Alejandro.
Started
Last updated

What you’ll achieve

Choose uploaded listing photos from thumbnail dropdowns in repeatable FormBuilder rows, then display the selected images.

My site

Platform
JReviews version

Add a photo choice to each row of a repeatable FormBuilder field. On the frontend edit form, users can choose from thumbnails of photos already uploaded to that listing. The output template displays the selected photos using their current published images, so a removed or unpublished photo no longer appears.

Upload photos to the listing, approve and publish them, then save and reopen its frontend edit form before you use the picker. Unsaved listings have no photos to choose. Each repeatable row keeps its own photo choice. The photo endpoint below is a URL that the picker opens to load this listing's available photos. The FormBuilder schema describes the rows and tells the picker which URL to use.

JReviews 6 Early Access

Enable Listing Form and Listing Detail Page in Early Access. The example uses overrides and native listing permissions.

Add the photo endpoint

Joomla. Create templates/jreviews_overrides/routes/web.php.

WordPress. Create jreviews_overrides/routes/web.php.

Add the route marked with +. Keep overrides enabled in JReviews configuration.

This route checks the current user's permission to update the requested listing before it reads any photos. The listing ID in the URL is an input, not proof of permission. Do not remove that check.

  • If routes/web.php already exists, add the marked lines at the end of the file. The copy button copies only those lines.
  • If you are creating routes/web.php, type the two dimmed lines first, then add the marked lines below them.
<?php
defined('MVC_FRAMEWORK') or die;

$this->app['router']->get('/formbuilder/listing-photos', function (\FWD\Illuminate\Http\Request $request) {
    $reply = static function (array $body, int $status = 200) {
        return fwd_response()->json($body, $status, [
            'Cache-Control' => 'private, no-store',
        ]);
    };
    $definition = static function (array $photos): array {
        return [
            'type' => 'string',
            'default' => '',
            'enumSource' => [[
                'source' => array_merge([
                    ['value' => '', 'title' => 'No photo'],
                ], $photos),
                'value' => '{{item.value}}',
                'title' => '{{item.title}}',
            ]],
        ];
    };

    $rawId = $request->input('listingId');
    if (! is_string($rawId) || ! preg_match('/^(0|[1-9][0-9]*)$/D', $rawId)) {
        return $reply(['error' => 'Invalid listing ID.'], 422);
    }
    $id = filter_var($rawId, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]);
    if ($id === false) {
        return $reply(['error' => 'Invalid listing ID.'], 422);
    }
    if ($id === 0) {
        return $reply($definition([]));
    }

    $listing = \JReviews\App\Models\Listing::find($id);
    $user = $request->user();
    if (! $listing || ! $user || ! $user->can('update', $listing)) {
        return $reply(['error' => 'Access denied.'], 403);
    }

    $photos = \JReviews\App\Models\Media::query()
        ->coreExtension()
        ->photo()
        ->published()
        ->notCommentMedia()
        ->where('listing_id', $listing->id)
        ->orderBy('ordering')
        ->orderBy('media_id')
        ->get()
        ->map(static function ($photo): array {
            return [
                'value' => $photo->id.'|'.$photo->small,
                'title' => $photo->title ?: $photo->filename,
            ];
        })
        ->all();

    return $reply($definition($photos));
});

Only published, approved, non-comment photos from the listing are returned. If your host, caching service, or CDN saves responses for reuse between visitors, exclude this photo URL. Its list of photos is private to users allowed to edit that listing.

Create the repeatable field

Create a listing custom field of type FormBuilder, named jr_photochoices. Enter photochoices in Name; JReviews adds the jr_ prefix. In the field editor, choose a listing field group. Open the listing type you want to edit and include that group in its Field Groups selection. You can reuse a group already associated with that listing type. Paste this JSON into its schema setting and leave the field's default value empty.

Joomla schema.

{
    "title": "Selected photos",
    "type": "array",
    "format": "table",
    "items": {
        "title": "Photo",
        "type": "object",
        "properties": {
            "photo": {
                "title": "Photo",
                "type": "string",
                "$ref": "/index.php?option=com_jreviews&format=raw&url=formbuilder/listing-photos&listingId=:listing_id"
            }
        }
    }
}

WordPress schema.

{
    "title": "Selected photos",
    "type": "array",
    "format": "table",
    "items": {
        "title": "Photo",
        "type": "object",
        "properties": {
            "photo": {
                "title": "Photo",
                "type": "string",
                "$ref": "/wp-admin/admin-ajax.php?action=jreviews_ajax&url=formbuilder/listing-photos&listingId=:listing_id"
            }
        }
    }
}

For a site in a subdirectory, add that prefix to the endpoint URL. JReviews replaces :listing_id with the current listing ID before it renders the schema.

The photo endpoint is for signed-in users editing a listing through the site form. The control-panel schema preview does not identify a listing, so it may show only No photo or fail to load the photo choices. Test the listing edit form on the site.

Each saved row contains a value such as 123|https://example.com/photo.jpg. Here, 123 is the photo's ID and the URL after | supplies its thumbnail preview. For public display, the output template looks up the current photo by ID instead of trusting that saved URL.

Add the hook marked with + to hooks.php in your override root.

  • If hooks.php already exists, add the marked lines at the end of the file. The copy button copies only those lines.
  • If you are creating hooks.php, type the two dimmed lines first, then add the marked lines below them.

Joomla hook.

<?php
defined('MVC_FRAMEWORK') or die;

fwd_add_action('jreviews:route_matched:listing_edit', static function (): void {
    fwd_app('assetloader')->addScript(
        'listing-photo-picker',
        'templates/jreviews_overrides/listing-photo-picker.js'
    );
}, 10, 0);

WordPress hook.

<?php
defined('MVC_FRAMEWORK') or die;

fwd_add_action('jreviews:route_matched:listing_edit', static function (): void {
    fwd_app('assetloader')->addScript(
        'listing-photo-picker',
        'jreviews_overrides/listing-photo-picker.js'
    );
}, 10, 0);

Install the thumbnail picker script after you add the output template below.

Render photos from current media records

Joomla. Create templates/jreviews_overrides/resources/views/field-output/jr_photochoices.blade.php.

WordPress. Create jreviews_overrides/resources/views/field-output/jr_photochoices.blade.php.

Leave the field's inline Blade output and custom template name settings empty so JReviews can find this field-name template.

The template uses the photo ID before | in the saved value above; an ID on its own also works. It ignores the saved URL and finds the current published photo belonging to this listing. Invalid rows, deleted photos, unpublished photos, comment media, and media from other listings produce no image.

@php
    $rows = is_array($data ?? null) ? $data : [];
    $ids = [];
    foreach ($rows as $row) {
        $stored = is_array($row) ? ($row['photo'] ?? null) : null;
        if (! is_string($stored) || ! preg_match('/^([1-9][0-9]*)(?:\|[^\r\n]+)?$/D', $stored, $match)) {
            continue;
        }
        $id = filter_var($match[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
        if ($id !== false) {
            $ids[] = $id;
        }
    }
    $photos = fwd_collect();
    if (($listing ?? null) instanceof \JReviews\App\Models\Listing && $listing->id && $ids) {
        $photos = \JReviews\App\Models\Media::query()
            ->coreExtension()
            ->photo()
            ->published()
            ->notCommentMedia()
            ->where('listing_id', $listing->id)
            ->whereIn('media_id', array_unique($ids))
            ->get()
            ->keyBy('id');
    }
@endphp
@foreach ($ids as $id)
    @php
        $photo = $photos->get($id);
        $src = $photo ? (string) $photo->small : '';
        $scheme = strtolower((string) parse_url($src, PHP_URL_SCHEME));
        $safe = $src !== '' && (
            in_array($scheme, ['http', 'https'], true) ||
            ($scheme === '' && str_starts_with($src, '/') && ! str_starts_with($src, '//'))
        );
    @endphp
    @if ($photo && $safe)
        <img src="{{ $src }}" alt="{{ $photo->title ?: $photo->filename }}" loading="lazy">
    @endif
@endforeach

The photos appear in the same order as the FormBuilder rows. You can select the same photo in more than one row. The template protects the image URL and title from being treated as page code. It also checks the saved choices again before display. Keep those checks even though the picker already limits the available photos; someone can submit values without using the picker.

When a saved photo no longer appears in the choices, select a replacement or No photo, then save. If a thumbnail URL changes, the saved choice may no longer appear in the dropdown. The output still resolves its ID, but you must reopen and reselect that row to store the current choice. Malformed values render nothing.

JReviews 5 and v6 Legacy

Add the photo endpoint

Joomla. Use templates/jreviews_overrides as the override root for the files below.

WordPress. Use jreviews_overrides as the override root for the files below.

Keep overrides enabled.

Add the macro marked with + to controllers/developer_controller_macros.php.

  • If controllers/developer_controller_macros.php already exists, add the marked lines at the end of the file. The copy button copies only those lines.
  • If you are creating controllers/developer_controller_macros.php, type the two dimmed lines first, then add the marked lines below them.
<?php
defined('MVC_FRAMEWORK') or die;

DeveloperController::macro('listingImages', function () {
    $reply = function (array $body, int $status = 200) {
        header('Cache-Control: private, no-store');
        return $this->response->json()->status($status)->array($body);
    };
    $rawId = $this->params['listingId'] ?? null;
    if (! is_string($rawId) || ! preg_match('/^(0|[1-9][0-9]*)$/D', $rawId)) {
        return $reply(['error' => 'Invalid listing ID.'], 422);
    }
    $id = filter_var($rawId, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]);
    if ($id === false) {
        return $reply(['error' => 'Invalid listing ID.'], 422);
    }
    $source = [['value' => '', 'title' => 'No photo']];
    if ($id > 0) {
        S2App::import('Model', ['media', 'everywhere_com_content'], 'jreviews');
        $listingModel = ClassRegistry::getClass('EverywhereComContentModel');
        $listing = $listingModel->findRow([
            'conditions' => ['Listing.'.EverywhereComContentModel::_LISTING_ID.' = '.$id],
        ]);
        if (! $listing || $this->auth->guest || ! $this->perm->__('listing')->setListing($listing)->canUpdate()) {
            return $reply(['error' => 'Access denied.'], 403);
        }
        $mediaModel = ClassRegistry::getClass('MediaModel');
        $photos = $mediaModel->findAll([
            'conditions' => [
                'Media.listing_id = '.$id,
                'Media.review_id = 0',
                'Media.extension = "com_content"',
                'Media.media_type = "photo"',
                'Media.published = 1',
                'Media.approved = 1',
            ],
            'order' => ['Media.ordering ASC', 'Media.media_id ASC'],
        ]);
        foreach ($photos as $photo) {
            $media = $photo['Media'];
            $source[] = [
                'value' => $media['media_id'].'|'.$media['media_url'],
                'title' => $media['title'] ?: $media['filename'],
            ];
        }
    }
    return $reply([
        'type' => 'string',
        'default' => '',
        'enumSource' => [[
            'source' => $source,
            'value' => '{{item.value}}',
            'title' => '{{item.title}}',
        ]],
    ]);
});

The endpoint checks that the signed-in user may edit the listing before it loads any photos. Exclude this photo URL from caches that reuse responses between visitors.

Create the repeatable field

Create a listing FormBuilder field named jr_photochoices. Enter photochoices in Name; JReviews adds the jr_ prefix. Choose a listing field group in the field editor. Open your listing type and include the same group in its Field Groups selection. An existing associated group also works. Paste this schema and leave its default value empty.

Joomla schema.

{
    "title": "Selected photos",
    "type": "array",
    "format": "table",
    "items": {
        "title": "Photo",
        "type": "object",
        "properties": {
            "photo": {
                "title": "Photo",
                "type": "string",
                "$ref": "/index.php?option=com_jreviews&format=raw&url=developer/listingImages&listingId=:photo_listing_id"
            }
        }
    }
}

WordPress schema.

{
    "title": "Selected photos",
    "type": "array",
    "format": "table",
    "items": {
        "title": "Photo",
        "type": "object",
        "properties": {
            "photo": {
                "title": "Photo",
                "type": "string",
                "$ref": "/wp-admin/admin-ajax.php?action=jreviews_ajax&url=developer/listingImages&listingId=:photo_listing_id"
            }
        }
    }
}

For a site in a subdirectory, add that prefix to the endpoint URL.

Create filters/listing_photo_picker.php in your override root. This filter fills in the ID for the current listing form and loads the shared picker script. Each form carries its own ID, so two open edit tabs do not overwrite a shared session value.

<?php

defined('MVC_FRAMEWORK') or die;

$photoPicker = function (array $viewVars, array $params): array {
    $id = (int) ($viewVars['listing']['Listing']['listing_id'] ?? 0);
    foreach ($viewVars['listing_fields'] ?? [] as $groupKey => $group) {
        $field = $group['Fields']['jr_photochoices'] ?? null;
        if (! is_array($field)) {
            continue;
        }
        $schema = $field['properties']['json_schema'] ?? [];
        if (! is_array($schema)) {
            continue;
        }
        $ref = $schema['items']['properties']['photo']['$ref'] ?? null;
        if (is_string($ref)) {
            $schema['items']['properties']['photo']['$ref'] = str_replace(':photo_listing_id', (string) $id, $ref);
            $viewVars['listing_fields'][$groupKey]['Fields']['jr_photochoices']['properties']['json_schema'] = $schema;
        }
    }
    $path = _CMS_NAME === 'wordpress' ? 'jreviews_overrides/' : 'templates/jreviews_overrides/';
    $url = rtrim(WWW_ROOT, '/').'/'.$path.'listing-photo-picker.js';
    S2Object::make('asset_manager')->addScript(
        'var script=document.createElement("script");script.src='.json_encode($url).';document.head.appendChild(script);',
        'listing-photo-picker',
        'addon'
    );
    return $viewVars;
};
foreach (['listings_create', 'listings_edit'] as $route) {
    Clickfwd\Hook\Filter::add('before_theme_render_viewvars_'.$route, $photoPicker, 10);
}

Install the shared thumbnail picker. Clear the JReviews file registry so it discovers the controller macro and filter. Test the frontend edit form, because the field configuration preview does not identify a listing.

Display selected photos in the field template

Create views/themes/mysite/fields_phpformat/photo_choices.thtml in your override root. Replace mysite with your active custom theme. Set the field's Template name to photo_choices, leave PHP output format empty, and clear the file registry.

<?php

defined('MVC_FRAMEWORK') or die;

$rows = json_decode((string) $text, true);
$rows = is_array($rows) ? $rows : [];
$ids = [];
foreach ($rows as $row) {
    $stored = is_array($row) ? ($row['photo'] ?? null) : null;
    if (! is_string($stored) || ! preg_match('/^([1-9][0-9]*)(?:\|[^\r\n]+)?$/D', $stored, $match)) {
        continue;
    }
    $id = filter_var($match[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
    if ($id !== false) {
        $ids[] = $id;
    }
}
$listingId = (int) ($entry['Listing']['listing_id'] ?? 0);
$photos = [];
if ($listingId > 0 && $ids) {
    S2App::import('Model', 'media', 'jreviews');
    $mediaModel = ClassRegistry::getClass('MediaModel');
    $records = $mediaModel->findAll([
        'conditions' => [
            'Media.listing_id = '.$listingId,
            'Media.media_id IN ('.implode(',', array_unique($ids)).')',
            'Media.review_id = 0',
            'Media.extension = "com_content"',
            'Media.media_type = "photo"',
            'Media.published = 1',
            'Media.approved = 1',
        ],
    ]);
    foreach ($records as $record) {
        $photos[$record['Media']['media_id']] = $record['Media'];
    }
}
foreach ($ids as $id) {
    $photo = $photos[$id] ?? null;
    $src = $photo ? (string) $photo['media_url'] : '';
    $scheme = strtolower((string) parse_url($src, PHP_URL_SCHEME));
    $safe = $src !== '' && (
        in_array($scheme, ['http', 'https'], true) ||
        ($scheme === '' && str_starts_with($src, '/') && ! str_starts_with($src, '//'))
    );
    if ($photo && $safe) {
        echo '<img src="'.htmlspecialchars($src, ENT_QUOTES, 'UTF-8').'" alt="'.htmlspecialchars($photo['title'] ?: $photo['filename'], ENT_QUOTES, 'UTF-8').'" loading="lazy">';
    }
}

The template ignores the saved URL. It resolves each saved media ID against the current listing's approved, published, non-comment photos. Removed, unpublished, invalid, and other-listing photos produce no image. Repeated selections display in row order.

See FormBuilder fields and output templates and legacy hooks for the related settings.

Install the thumbnail picker

After adding the endpoint, field schema, and output template for your JReviews version, install the script below. Each repeatable row uses the same script.

Joomla. Save the script below as templates/jreviews_overrides/listing-photo-picker.js.

WordPress. Save the script below as jreviews_overrides/listing-photo-picker.js.

The script connects each thumbnail dropdown to its row's photo select.

(() => {
    if (window.jrListingPhotoPicker) return;
    window.jrListingPhotoPicker = true;
    const selector = 'select[name^="fb-jr_photochoices["][name$="[photo]"], [jr-formbuilder]:has([jr-model][name="data[Field][Listing][jr_photochoices]"]) select[name^="root["][name$="[photo]"]';
    const controls = new Map();
    let queued = false;
    const watchedEditors = new WeakSet();

    document.addEventListener('jreviews:formbuilder:ready', event => {
        const editor = event.detail?.editor;
        if (!editor || watchedEditors.has(editor)) return;
        watchedEditors.add(editor);
        editor.on('change', queueRefresh);
        queueRefresh();
    });

    function imageUrl(value) {
        const match = /^([1-9][0-9]*)\|(.+)$/.exec(value);
        if (!match) return null;
        try {
            const url = new URL(match[2], document.baseURI);
            return ['http:', 'https:'].includes(url.protocol) ? url.href : null;
        } catch {
            return null;
        }
    }

    function refresh() {
        queued = false;
        for (const [select, control] of controls) {
            if (!select.isConnected || !select.matches(selector)) {
                control.details.remove();
                controls.delete(select);
            }
        }
        document.querySelectorAll(selector).forEach(select => {
            let control = controls.get(select);
            if (!control) {
                const details = document.createElement('details');
                const summary = document.createElement('summary');
                const choices = document.createElement('div');
                details.append(summary, choices);
                select.after(details);
                control = { details, summary, choices, signature: null };
                controls.set(select, control);
            }
            const options = Array.from(select.options);
            const disabled = select.matches(':disabled');
            const signature = JSON.stringify([
                select.value, disabled,
                options.map(option => [option.value, option.text, option.disabled])
            ]);
            if (control.signature === signature && control.details.isConnected) return;
            control.signature = signature;
            if (control.details.previousElementSibling !== select) select.after(control.details);
            control.summary.textContent = disabled ? 'Photo choices unavailable' :
                `Choose thumbnail: ${select.selectedOptions[0]?.text || 'No photo'}`;
            control.choices.replaceChildren();
            for (const option of options) {
                const button = document.createElement('button');
                button.type = 'button';
                button.disabled = disabled || option.disabled;
                button.setAttribute('aria-pressed', String(option.selected));
                button.style.cssText = 'display:flex;align-items:center;gap:.5rem;margin:.25rem;padding:.5rem';
                const src = imageUrl(option.value);
                if (src) {
                    const image = document.createElement('img');
                    image.src = src;
                    image.alt = '';
                    image.width = 48;
                    image.height = 48;
                    image.style.objectFit = 'cover';
                    image.addEventListener('error', () => image.remove(), { once: true });
                    button.append(image);
                }
                const title = document.createElement('span');
                title.textContent = option.text || 'No photo';
                button.append(title);
                button.addEventListener('click', () => {
                    if (select.matches(':disabled') || option.disabled) return;
                    select.value = option.value;
                    select.dispatchEvent(new Event('input', { bubbles: true }));
                    select.dispatchEvent(new Event('change', { bubbles: true }));
                    control.details.open = false;
                    control.summary.focus();
                    queueRefresh();
                });
                control.choices.append(button);
            }
        });
    }

    function queueRefresh() {
        if (queued) return;
        queued = true;
        queueMicrotask(refresh);
    }

    function start() {
        if (window.jQuery) {
            window.jQuery(document).on('jrFormBuilderValidated', '.jr-page', queueRefresh);
        }
        new MutationObserver(records => {
            const relevant = records.some(record =>
                record.target instanceof Element &&
                (record.target.matches(selector) || controls.has(record.target) || record.target.closest(selector) ||
                    record.type === 'attributes' && record.target.matches('fieldset')) ||
                record.target.parentElement?.closest(selector) ||
                Array.from(record.addedNodes).concat(Array.from(record.removedNodes)).some(node =>
                    node instanceof Element && (node.matches(selector) || node.querySelector(selector)))
            );
            if (relevant) queueRefresh();
        }).observe(document.body, {
            childList: true, subtree: true, attributes: true,
            attributeFilter: ['disabled', 'selected', 'value', 'name'],
            characterData: true
        });
        document.addEventListener('change', event => {
            if (event.target instanceof Element && event.target.matches(selector)) queueRefresh();
        }, true);
        document.addEventListener('reset', () => setTimeout(queueRefresh, 0));
        refresh();
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', start, { once: true });
    } else {
        start();
    }
})();

The original select remains visible and saves the photo choice. Open Choose thumbnail to use the thumbnail buttons. Native buttons support keyboard activation. Each row has its own dropdown. The thumbnail buttons refresh when photo choices finish loading and when you add, remove, move, or edit rows. The select still works when the custom script is disabled.

If you rename jr_photochoices or its photo property, update the selector. Custom scripts that change select.value must dispatch a bubbling change event.

Check photo selection, saving, and display

Use an existing listing with two approved, published photos and a user who can edit it.

  1. Open its frontend edit form. Add two rows and choose different thumbnails.
  2. Change one choice with the original select. Confirm the dropdown shows the new selection.
  3. Save and reopen the listing. Confirm both rows retain their choices.
  4. Add and remove rows. Confirm each remaining row has one thumbnail dropdown and updates its own select.
  5. Display the listing. Confirm the photos appear in row order.
  6. Unpublish or remove a selected photo. Confirm its output disappears. Reopen the edit form and clear or replace that choice.

If the photo choices fail to load, open the browser's developer tools, select Network, and reload the listing edit form. Select the request containing listing-photos or listingImages. Check its URL, status, and Response. A 403 means the user was not accepted as an editor of that listing. A response containing a whole HTML page instead of the photo-choice JSON usually means the CMS URL is wrong or JReviews did not handle it. Check the URL from your schema, including any site subdirectory. Keep the permission check in place.

See FormBuilder custom fields, field output templates, and hooks for the related JReviews settings.

Learn more