JReviews logo
Guides My site
← All guides Community guide

Make FormBuilder opening hours searchable

A Josh Ant
Thread started by Alex.1. Contributors Josh, Ant.
Thread started
Last updated

What you’ll achieve

Keep compact opening-hours entry and search weekly availability in half-hour slots.

My site

Platform
JReviews version

Enter a listing's weekly opening intervals in FormBuilder, then filter listings by the half-hour slots inside those intervals. Monday 10:00 to 12:00 becomes 10:00, 10:30, 11:00, and 11:30. A Thursday lunch break stays out of the search results.

JReviews 6 Early Access

Enable the Early Access Listing Form. For the Blade output below, also enable the Early Access Listing Detail Page.

Create the opening-hours fields

In JReviews > Setup > Fields, create a listing field named jr_openinghours with type FormBuilder. Choose a listing field group such as Opening hours in the field editor. Open your business listing type and include that group in its Field Groups selection. Paste this schema into its schema editor, update the preview, and save the field with an empty default array [].

{
  "type": "array",
  "title": "Opening hours",
  "maxItems": 42,
  "items": {
    "type": "object",
    "additionalProperties": false,
    "required": [
      "day",
      "open",
      "close"
    ],
    "properties": {
      "day": {
        "type": "string",
        "title": "Day",
        "enum": [
          "mon",
          "tue",
          "wed",
          "thu",
          "fri",
          "sat",
          "sun"
        ]
      },
      "open": {
        "type": "string",
        "title": "Opens (HH:MM)",
        "pattern": "^(?:[01][0-9]|2[0-3]):(?:00|30)$"
      },
      "close": {
        "type": "string",
        "title": "Closes (HH:MM)",
        "pattern": "^(?:(?:[01][0-9]|2[0-3]):(?:00|30)|24:00)$"
      }
    }
  }
}

Each row has a weekday, an opening time, and a closing time. Add another row for a second interval on the same day. Remove all rows for a closed week. Do not add a row for a closed day. Do not add an empty row for it.

Use the business's local time in 24-hour format, with minutes set to 00 or 30. The opening time starts the first searchable slot; the closing time is not another slot. For example, 10:00 to 12:00 includes 11:30 to 12:00, but not 12:00 to 12:30. 24:00 is allowed only as a closing time and means midnight at the end of that weekday. For overnight hours, split Monday 22:00 to Tuesday 02:00 into Monday 22:00 to 24:00 and Tuesday 00:00 to 02:00. Equal times, reversed intervals, quarter-hour times, incomplete rows, and unknown weekdays are rejected. The limit is 42 intervals per listing and 16,384 bytes of JSON. Overlapping intervals merge without duplicate slots.

This example describes a repeating local week. It does not handle dates, holidays, time-zone conversion, or reservations.

Create these seven listing fields with type Checkbox:

Field name Title
jr_openmon Monday availability
jr_opentue Tuesday availability
jr_openwed Wednesday availability
jr_openthu Thursday availability
jr_openfri Friday availability
jr_opensat Saturday availability
jr_opensun Sunday availability

Place all eight fields in the Opening hours listing field group. In the business listing type settings, include that group in Field Groups. If you reuse an existing associated group, keep all eight fields in that group. Give them the same write permissions. Keep the fields published and optional, with no field or field-group dependencies. Disable Click2Add on the Checkbox fields. Leave any maximum selected-options limit empty or set it to 48. Enable search and visitor read access on all seven Checkbox fields. Disable their output in list and detail views so the FormBuilder remains the compact public display.

Use maximum characters 255 for each Checkbox field. All 48 four-character values take 241 characters in JReviews' storage format. Keeping weekdays in separate fields avoids putting the entire week into one long field value.

Keep all eight fields active in the submission form. Do not remove the Checkbox controls from the template or disable them with JavaScript. After the checks below pass, you can hide their form wrappers in your theme. Visual hiding does not enforce permissions. The callbacks check write permission on every field and do not grant any additional access.

Add all 48 time options to each Checkbox field

Open the field's options screen and create one option for every row below. Enter Text as shown. Enter Value explicitly, preserving leading zeroes. Keep Default value off and leave option relations empty. Save each option. Repeat the complete table for every weekday field.

These are ordinary saved field options. This recipe does not assume a bulk importer, create options during listing saves, or require a database edit. There are 336 options in total. Complete them before enabling the callbacks. The callback rejects a submitted interval if any of its required options is missing.

Text Value
00:00 to 00:30 0000
00:30 to 01:00 0030
01:00 to 01:30 0100
01:30 to 02:00 0130
02:00 to 02:30 0200
02:30 to 03:00 0230
03:00 to 03:30 0300
03:30 to 04:00 0330
04:00 to 04:30 0400
04:30 to 05:00 0430
05:00 to 05:30 0500
05:30 to 06:00 0530
06:00 to 06:30 0600
06:30 to 07:00 0630
07:00 to 07:30 0700
07:30 to 08:00 0730
08:00 to 08:30 0800
08:30 to 09:00 0830
09:00 to 09:30 0900
09:30 to 10:00 0930
10:00 to 10:30 1000
10:30 to 11:00 1030
11:00 to 11:30 1100
11:30 to 12:00 1130
12:00 to 12:30 1200
12:30 to 13:00 1230
13:00 to 13:30 1300
13:30 to 14:00 1330
14:00 to 14:30 1400
14:30 to 15:00 1430
15:00 to 15:30 1500
15:30 to 16:00 1530
16:00 to 16:30 1600
16:30 to 17:00 1630
17:00 to 17:30 1700
17:30 to 18:00 1730
18:00 to 18:30 1800
18:30 to 19:00 1830
19:00 to 19:30 1900
19:30 to 20:00 1930
20:00 to 20:30 2000
20:30 to 21:00 2030
21:00 to 21:30 2100
21:30 to 22:00 2130
22:00 to 22:30 2200
22:30 to 23:00 2230
23:00 to 23:30 2300
23:30 to 24:00 2330

Each label names the start of a half-hour interval. 10:00 to 10:30 stores 1000. 23:30 to 24:00 stores 2330. There is no 2400 option.

Show the compact intervals

In jr_openinghours, paste this into Blade template code. It uses the saved weekday, opening time, and closing time. Leave a separately selected Field output Blade template empty.

@php
$rows = json_decode($value, true);
$days = ['mon' => 'Monday', 'tue' => 'Tuesday', 'wed' => 'Wednesday', 'thu' => 'Thursday', 'fri' => 'Friday', 'sat' => 'Saturday', 'sun' => 'Sunday'];
@endphp
@if (is_array($rows) && $rows)
<ul>
	@foreach ($rows as $row)
		@if (is_array($row) && isset($days[$row['day'] ?? '']) && is_string($row['open'] ?? null) && is_string($row['close'] ?? null))
		<li>{{ $days[$row['day']] }} {{ $row['open'] }} to {{ $row['close'] }}</li>
		@endif
	@endforeach
</ul>
@endif

Add the save callbacks in overrides

Add the PHP example to templates/jreviews_overrides/hooks.php.

Add the PHP example to jreviews_overrides/hooks.php.

Add the code marked with +. Install this example once. Remove any earlier copy of these hours callbacks and helper functions before replacing it. Keep it in overrides rather than changing JReviews core files.

  • 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.
<?php
defined('MVC_FRAMEWORK') or die;

function communityOpeningHoursDays(): array
{
	return ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
}

function communityOpeningHoursSlots($raw): array
{
	if (!is_string($raw) || strlen($raw) > 16384) {
		throw new InvalidArgumentException('Enter opening hours as a JSON array of at most 42 complete intervals.');
	}
	$raw = trim($raw);
	$rows = $raw === '' ? [] : json_decode($raw);
	if (($raw !== '' && ($raw[0] !== '[' || json_last_error() !== JSON_ERROR_NONE)) || !is_array($rows) || count($rows) > 42) {
		throw new InvalidArgumentException('Enter opening hours as a JSON array of at most 42 complete intervals.');
	}
	$slots = array_fill_keys(communityOpeningHoursDays(), []);
	foreach ($rows as $row) {
		if (!$row instanceof stdClass) {
			throw new InvalidArgumentException('Every opening-hours row needs day, open, and close.');
		}
		$keys = array_keys(get_object_vars($row));
		sort($keys);
		if ($keys !== ['close', 'day', 'open'] || !is_string($row->day) || !array_key_exists($row->day, $slots)
			|| !is_string($row->open) || !is_string($row->close)
			|| !preg_match('/^(?:[01][0-9]|2[0-3]):(?:00|30)$/D', $row->open)
			|| !preg_match('/^(?:(?:[01][0-9]|2[0-3]):(?:00|30)|24:00)$/D', $row->close)) {
			throw new InvalidArgumentException('Use mon to sun and half-hour times HH:00 or HH:30. Only close may be 24:00.');
		}
		$start = (int) substr($row->open, 0, 2) * 60 + (int) substr($row->open, 3, 2);
		$end = (int) substr($row->close, 0, 2) * 60 + (int) substr($row->close, 3, 2);
		if ($end <= $start) {
			throw new InvalidArgumentException('Closing time must be later on the same day. Split overnight hours into two days.');
		}
		for ($minute = $start; $minute < $end; $minute += 30) {
			$value = sprintf('%02d%02d', intdiv($minute, 60), $minute % 60);
			$slots[$row->day][$value] = $value;
		}
	}
	foreach ($slots as $day => $values) {
		$slots[$day] = array_values($values);
		sort($slots[$day], SORT_STRING);
	}
	return $slots;
}

function communityOpeningHoursCheckFields(array $slots, array $availableNames): void
{
	$names = ['jr_openinghours'];
	foreach (communityOpeningHoursDays() as $day) {
		$names[] = 'jr_open'.$day;
	}
	if (array_diff($names, $availableNames)) {
		throw new InvalidArgumentException('Assign all eight opening-hours fields to this listing type and keep them active in the form.');
	}
	$fields = \JReviews\App\Models\Field::with('field_options')->whereIn('name', $names)->get()->keyBy('name');
	foreach ($names as $name) {
		$field = $fields->get($name);
		$type = $name === 'jr_openinghours' ? 'formbuilder' : 'checkboxes';
		if (!$field || $field->type !== $type || fwd_auth()->user()->cannot('write', $field)) {
			throw new InvalidArgumentException('Opening hours need the FormBuilder and all seven writable Checkbox fields. Ask the site administrator to check their setup.');
		}
	}
	foreach ($slots as $day => $values) {
		$options = array_map('strval', $fields->get('jr_open'.$day)->field_options->pluck('value')->all());
		if (array_diff($values, $options)) {
			throw new InvalidArgumentException('An opening-hours Checkbox option is missing. Ask the site administrator to complete the time options.');
		}
	}
}

fwd_add_action('jreviews:listing_form.validation', function ($validator, $creating) {
	$validator->after(function ($validator) {
		$fields = $validator->getData()['fields'] ?? [];
		if (!is_array($fields) || !array_key_exists('jr_openinghours', $fields)) {
			return;
		}
		try {
			$slots = communityOpeningHoursSlots($fields['jr_openinghours']);
			$available = array_map(function ($name) { return substr($name, 7); }, array_keys($validator->getRules()));
			communityOpeningHoursCheckFields($slots, $available);
		} catch (InvalidArgumentException $error) {
			$validator->errors()->add('fields.jr_openinghours', $error->getMessage());
		}
	});
}, 20, 2);

fwd_add_filter('jreviews:listing.data_before_save', function (array $data, $listing): array {
	if (!fwd_request()->inFrontend() || !array_key_exists('jr_openinghours', $data['fields'] ?? [])) {
		return $data;
	}
	$slots = communityOpeningHoursSlots($data['fields']['jr_openinghours']);
	communityOpeningHoursCheckFields($slots, $listing->getFields()->pluck('name')->all());
	foreach ($slots as $day => $values) {
		$data['fields']['jr_open'.$day] = $values;
	}
	return $data;
}, 20, 2);

The code rejects invalid intervals before saving. For a valid submission, it selects the matching half-hour options in each weekday Checkbox field. It works on new listings and edits; JReviews saves the selections in its normal format.

Filter listings by a half-hour

In Configuration > Early Access Settings, enable Listing List Pages so the result page uses live filtering. Create or retain a published JReviews Advanced Search page for the search-results route.

In Setup > Site Widgets, create a Listing Filters widget and publish it. In its Filter Builder, add a Custom Field element for Thursday (jr_openthu). Set the label to Thursday availability and Display As to Options. This shows the saved half-hour choices with an Any/All match toggle. Set Visible Options to 0 to show every option, or keep a shorter list with Show more.

Keep Auto-detect from Page enabled. The business list or search-results page must use the business listing type that contains the opening-hours fields. Add another weekday by adding another Custom Field element for that day's Checkbox field.

Publish a JReviews Universal Module. Select the saved Listing Filters widget in JReviews Widget and choose its module position. Assign the module to your business listing and Advanced Search menu items.

Add a (JReviews) Universal Widget to a sidebar displayed on your business listing and search-results pages. Select the saved Listing Filters widget in JReviews Widget.

Open the public result page and confirm that Thursday availability shows the half-hour options you created. See Listing Filters for the remaining widget settings.

Create these three published listings through the applicable frontend listing form:

Listing Intervals
A Monday 10:00 to 12:00; Thursday 09:00 to 12:00 and 15:00 to 18:00
B Thursday 12:00 to 15:00
C Friday 15:00 to 18:00

Listing A's FormBuilder JSON is:

[{"day":"mon","open":"10:00","close":"12:00"},{"day":"thu","open":"09:00","close":"12:00"},{"day":"thu","open":"15:00","close":"18:00"}]

Reopen A. Monday must contain 1000, 1030, 1100, and 1130. Thursday must contain 0900, 0930, 1000, 1030, 1100, 1130, 1500, 1530, 1600, 1630, 1700, and 1730. The other weekdays must be empty. Its public display must show the three compact intervals.

On the listing page, select 15:30 to 16:00 in the Thursday filter. Only A must appear. Clear the filter, then select 12:30 to 13:00. Only B must appear. 18:00 to 18:30 must match none of these listings. C must never match a Thursday slot.

To find a business open for a longer interval, choose All in the Thursday filter, then select both 15:00 to 15:30 and 15:30 to 16:00. The result must contain both slots. Any instead matches a business open during either selected slot. Keep every consecutive half-hour checked when searching for a longer continuous interval. Selecting only its endpoints does not establish that the business stays open between them.

Check edits, clearing, validation, and access

  1. Change A to Thursday 15:00 to 16:00. Save and reopen it. Monday must clear, and Thursday must contain only 1500 and 1530. A must stop matching Thursday 16:00 to 16:30.
  2. Remove all FormBuilder rows and save []. All seven Checkbox fields must clear, and A must stop matching every availability filter. An empty source string also clears the week.
  3. Submit an incomplete row, malformed JSON, an unknown weekday, a 10:15 opening time, or a reversed interval. The form must report an error. No listing changes may persist. A valid row beside an invalid row must not create partial search values.
  4. Try Monday 00:00 to 24:00. Monday must contain all 48 options, including 0000 and 2330. Change it to Monday 23:30 to 24:00. Only 2330 must remain.
  5. Test each user group that can create or edit listings. A user without field write permission must not gain it through the callback. Test an unrelated listing type without these fields too.

The normal JReviews listing, field, and option validation still applies. Whenever a form submits valid Opening hours, the customization replaces the selections in all seven weekday fields. It does not add them to the previous selections. If a form does not submit Opening hours, this conversion does not change the weekday fields.

Existing listings are not rebuilt automatically. Resave them through this form to create the search values. Imports, direct database writes, and other submission paths need a separate integration. These frontend hooks do not update those paths.

JReviews 5 and v6 Legacy

Create the opening-hours fields

In JReviews > Setup > Fields, create a listing field named jr_openinghours with type FormBuilder. Choose a listing field group such as Opening hours in the field editor. Open your business listing type and include that group in its Field Groups selection. Paste this schema into its schema editor, update the preview, and save the field with an empty default array [].

{
  "type": "array",
  "title": "Opening hours",
  "maxItems": 42,
  "items": {
    "type": "object",
    "additionalProperties": false,
    "required": [
      "day",
      "open",
      "close"
    ],
    "properties": {
      "day": {
        "type": "string",
        "title": "Day",
        "enum": [
          "mon",
          "tue",
          "wed",
          "thu",
          "fri",
          "sat",
          "sun"
        ]
      },
      "open": {
        "type": "string",
        "title": "Opens (HH:MM)",
        "pattern": "^(?:[01][0-9]|2[0-3]):(?:00|30)$"
      },
      "close": {
        "type": "string",
        "title": "Closes (HH:MM)",
        "pattern": "^(?:(?:[01][0-9]|2[0-3]):(?:00|30)|24:00)$"
      }
    }
  }
}

Each row has a weekday, an opening time, and a closing time. Add another row for a second interval on the same day. Remove all rows for a closed week. Do not add a row for a closed day. Do not add an empty row for it.

Use the business's local time in 24-hour format, with minutes set to 00 or 30. The opening time starts the first searchable slot; the closing time is not another slot. For example, 10:00 to 12:00 includes 11:30 to 12:00, but not 12:00 to 12:30. 24:00 is allowed only as a closing time and means midnight at the end of that weekday. For overnight hours, split Monday 22:00 to Tuesday 02:00 into Monday 22:00 to 24:00 and Tuesday 00:00 to 02:00. Equal times, reversed intervals, quarter-hour times, incomplete rows, and unknown weekdays are rejected. The limit is 42 intervals per listing and 16,384 bytes of JSON. Overlapping intervals merge without duplicate slots.

This example describes a repeating local week. It does not handle dates, holidays, time-zone conversion, or reservations.

Create these seven listing fields with type Checkbox:

Field name Title
jr_openmon Monday availability
jr_opentue Tuesday availability
jr_openwed Wednesday availability
jr_openthu Thursday availability
jr_openfri Friday availability
jr_opensat Saturday availability
jr_opensun Sunday availability

Place all eight fields in the Opening hours listing field group. In the business listing type settings, include that group in Field Groups. If you reuse an existing associated group, keep all eight fields in that group. Give them the same write permissions. Keep the fields published and optional, with no field or field-group dependencies. Disable Click2Add on the Checkbox fields. Leave any maximum selected-options limit empty or set it to 48. Enable search and visitor read access on all seven Checkbox fields. Disable their output in list and detail views so the FormBuilder remains the compact public display.

Use maximum characters 255 for each Checkbox field. All 48 four-character values take 241 characters in JReviews' storage format. Keeping weekdays in separate fields avoids putting the entire week into one long field value.

Keep all eight fields active in the submission form. Do not remove the Checkbox controls from the template or disable them with JavaScript. After the checks below pass, you can hide their form wrappers in your theme. Visual hiding does not enforce permissions. The callbacks check write permission on every field and do not grant any additional access.

Add all 48 time options to each Checkbox field

Open the field's options screen and create one option for every row below. Enter Text as shown. Enter Value explicitly, preserving leading zeroes. Keep Default value off and leave option relations empty. Save each option. Repeat the complete table for every weekday field.

These are ordinary saved field options. This recipe does not assume a bulk importer, create options during listing saves, or require a database edit. There are 336 options in total. Complete them before enabling the callbacks. The callback rejects a submitted interval if any of its required options is missing.

Text Value
00:00 to 00:30 0000
00:30 to 01:00 0030
01:00 to 01:30 0100
01:30 to 02:00 0130
02:00 to 02:30 0200
02:30 to 03:00 0230
03:00 to 03:30 0300
03:30 to 04:00 0330
04:00 to 04:30 0400
04:30 to 05:00 0430
05:00 to 05:30 0500
05:30 to 06:00 0530
06:00 to 06:30 0600
06:30 to 07:00 0630
07:00 to 07:30 0700
07:30 to 08:00 0730
08:00 to 08:30 0800
08:30 to 09:00 0830
09:00 to 09:30 0900
09:30 to 10:00 0930
10:00 to 10:30 1000
10:30 to 11:00 1030
11:00 to 11:30 1100
11:30 to 12:00 1130
12:00 to 12:30 1200
12:30 to 13:00 1230
13:00 to 13:30 1300
13:30 to 14:00 1330
14:00 to 14:30 1400
14:30 to 15:00 1430
15:00 to 15:30 1500
15:30 to 16:00 1530
16:00 to 16:30 1600
16:30 to 17:00 1630
17:00 to 17:30 1700
17:30 to 18:00 1730
18:00 to 18:30 1800
18:30 to 19:00 1830
19:00 to 19:30 1900
19:30 to 20:00 1930
20:00 to 20:30 2000
20:30 to 21:00 2030
21:00 to 21:30 2100
21:30 to 22:00 2130
22:00 to 22:30 2200
22:30 to 23:00 2230
23:00 to 23:30 2300
23:30 to 24:00 2330

Each label names the start of a half-hour interval. 10:00 to 10:30 stores 1000. 23:30 to 24:00 stores 2330. There is no 2400 option.

Show the compact intervals

In jr_openinghours, paste this into PHP output format, without an opening PHP tag. Clear any selected legacy output template. It displays the saved intervals with escaped text.

$rows = json_decode($value, true);
$days = ['mon' => 'Monday', 'tue' => 'Tuesday', 'wed' => 'Wednesday', 'thu' => 'Thursday', 'fri' => 'Friday', 'sat' => 'Saturday', 'sun' => 'Sunday'];
$output = [];
foreach (is_array($rows) ? $rows : [] as $row) {
	if (!is_array($row) || !isset($days[$row['day'] ?? '']) || !is_string($row['open'] ?? null) || !is_string($row['close'] ?? null)) {
		continue;
	}
	$label = $days[$row['day']].' '.$row['open'].' to '.$row['close'];
	$output[] = '<li>'.htmlspecialchars($label, ENT_QUOTES, 'UTF-8').'</li>';
}
return $output ? '<ul>'.implode('', $output).'</ul>' : '';

Add the save callbacks in overrides

Add the PHP example to templates/jreviews_overrides/filters/filter_functions.php.

Add the PHP example to jreviews_overrides/filters/filter_functions.php.

Add the code marked with +. Install this example once. Remove any earlier copy of these hours callbacks and helper functions before replacing it. Keep it in overrides rather than changing JReviews core files.

  • If filter_functions.php already 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;

function communityLegacyOpeningHoursDays(): array
{
	return ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
}

function communityLegacyOpeningHoursSlots($raw): array
{
	if (!is_string($raw) || strlen($raw) > 16384) {
		throw new InvalidArgumentException('Enter opening hours as a JSON array of at most 42 complete intervals.');
	}
	$raw = trim($raw);
	$rows = $raw === '' ? [] : json_decode($raw);
	if (($raw !== '' && ($raw[0] !== '[' || json_last_error() !== JSON_ERROR_NONE)) || !is_array($rows) || count($rows) > 42) {
		throw new InvalidArgumentException('Enter opening hours as a JSON array of at most 42 complete intervals.');
	}
	$slots = array_fill_keys(communityLegacyOpeningHoursDays(), []);
	foreach ($rows as $row) {
		if (!$row instanceof stdClass) {
			throw new InvalidArgumentException('Every opening-hours row needs day, open, and close.');
		}
		$keys = array_keys(get_object_vars($row));
		sort($keys);
		if ($keys !== ['close', 'day', 'open'] || !is_string($row->day) || !array_key_exists($row->day, $slots)
			|| !is_string($row->open) || !is_string($row->close)
			|| !preg_match('/^(?:[01][0-9]|2[0-3]):(?:00|30)$/D', $row->open)
			|| !preg_match('/^(?:(?:[01][0-9]|2[0-3]):(?:00|30)|24:00)$/D', $row->close)) {
			throw new InvalidArgumentException('Use mon to sun and half-hour times HH:00 or HH:30. Only close may be 24:00.');
		}
		$start = (int) substr($row->open, 0, 2) * 60 + (int) substr($row->open, 3, 2);
		$end = (int) substr($row->close, 0, 2) * 60 + (int) substr($row->close, 3, 2);
		if ($end <= $start) {
			throw new InvalidArgumentException('Closing time must be later on the same day. Split overnight hours into two days.');
		}
		for ($minute = $start; $minute < $end; $minute += 30) {
			$value = sprintf('%02d%02d', intdiv($minute, 60), $minute % 60);
			$slots[$row->day][$value] = $value;
		}
	}
	foreach ($slots as $day => $values) {
		$slots[$day] = array_values($values);
		sort($slots[$day], SORT_STRING);
	}
	return $slots;
}

function communityLegacyOpeningHoursCheckFields(array $slots, array $availableNames): void
{
	$names = ['jr_openinghours'];
	foreach (communityLegacyOpeningHoursDays() as $day) {
		$names[] = 'jr_open'.$day;
	}
	if (array_diff($names, $availableNames)) {
		throw new InvalidArgumentException('Assign all eight opening-hours fields to this listing type and keep them active in the form.');
	}
	$fields = \JReviews\App\Models\Field::with('field_options')->whereIn('name', $names)->get()->keyBy('name');
	foreach ($names as $name) {
		$field = $fields->get($name);
		$type = $name === 'jr_openinghours' ? 'formbuilder' : 'checkboxes';
		if (!$field || $field->type !== $type || fwd_auth()->user()->cannot('write', $field)) {
			throw new InvalidArgumentException('Opening hours need the FormBuilder and all seven writable Checkbox fields. Ask the site administrator to check their setup.');
		}
	}
	foreach ($slots as $day => $values) {
		$options = array_map('strval', $fields->get('jr_open'.$day)->field_options->pluck('value')->all());
		if (array_diff($values, $options)) {
			throw new InvalidArgumentException('An opening-hours Checkbox option is missing. Ask the site administrator to complete the time options.');
		}
	}
}

Clickfwd\Hook\Filter::add('before_filter_request_listings__save', function ($request, $params) {
	$fields = $request['data']['Field']['Listing'] ?? [];
	if (!is_array($fields) || !array_key_exists('jr_openinghours', $fields)) {
		return $request;
	}
	try {
		$slots = communityLegacyOpeningHoursSlots($fields['jr_openinghours']);
	} catch (InvalidArgumentException $error) {
		$slots = array_fill_keys(communityLegacyOpeningHoursDays(), []);
	}
	foreach ($slots as $day => $values) {
		$request['data']['Field']['Listing']['jr_open'.$day] = $values;
	}
	return $request;
});

Clickfwd\Hook\Filter::add('listing_submit_validation', function ($validation, $params) {
	$fields = $params['data']['Field']['Listing'] ?? [];
	if (!is_array($fields) || !array_key_exists('jr_openinghours', $fields)) {
		return $validation;
	}
	try {
		$slots = communityLegacyOpeningHoursSlots($fields['jr_openinghours']);
		$typeId = (int) ($params['data']['ListingType']['listing_type_id'] ?? 0);
		$type = \JReviews\App\Models\ListingType::find($typeId);
		communityLegacyOpeningHoursCheckFields($slots, $type ? $type->getFields()->pluck('name')->all() : []);
	} catch (InvalidArgumentException $error) {
		$validation[] = $error->getMessage();
	}
	return $validation;
});

The code selects the matching half-hour options before JReviews checks and saves the form. Invalid intervals or missing options block the entire save, including the calculated Checkbox selections. The previously saved listing remains unchanged. JReviews saves valid selections in its normal format.

Filter listings by a half-hour

Create or retain the JReviews Advanced Search menu so search results have a route.

Publish the JReviews Listings Advanced Filtering module. Assign it to the business listings page and the search results page.

Publish the JReviews Listings Advanced Filtering widget. Display it on the business listings page and the search results page.

Under Theme customization, enable the module theme and add this filter shortcode:

[filter name="jr_openthu" label="Thursday availability" display_as="checkbox" match_type="all" match_switch="0"]

The same pattern adds another weekday filter by changing the field name and label. Keep the module's basic scope on the business listing type. Do not enable unrelated category filters for this check.

Create these three published listings through the applicable frontend listing form:

Listing Intervals
A Monday 10:00 to 12:00; Thursday 09:00 to 12:00 and 15:00 to 18:00
B Thursday 12:00 to 15:00
C Friday 15:00 to 18:00

Listing A's FormBuilder JSON is:

[{"day":"mon","open":"10:00","close":"12:00"},{"day":"thu","open":"09:00","close":"12:00"},{"day":"thu","open":"15:00","close":"18:00"}]

Reopen A. Monday must contain 1000, 1030, 1100, and 1130. Thursday must contain 0900, 0930, 1000, 1030, 1100, 1130, 1500, 1530, 1600, 1630, 1700, and 1730. The other weekdays must be empty. Its public display must show the three compact intervals.

On the listing page, select 15:30 to 16:00 in the Thursday filter. Only A must appear. Clear the filter, then select 12:30 to 13:00. Only B must appear. 18:00 to 18:30 must match none of these listings. C must never match a Thursday slot.

Selecting both 15:00 to 15:30 and 15:30 to 16:00 requires both slots because match_type="all". Keep every consecutive half-hour checked when searching for a longer continuous interval. Selecting only its endpoints does not establish that the business stays open between them.

Check edits, clearing, validation, and access

  1. Change A to Thursday 15:00 to 16:00. Save and reopen it. Monday must clear, and Thursday must contain only 1500 and 1530. A must stop matching Thursday 16:00 to 16:30.
  2. Remove all FormBuilder rows and save []. All seven Checkbox fields must clear, and A must stop matching every availability filter. An empty source string also clears the week.
  3. Submit an incomplete row, malformed JSON, an unknown weekday, a 10:15 opening time, or a reversed interval. The form must report an error. No listing changes may persist. A valid row beside an invalid row must not create partial search values.
  4. Try Monday 00:00 to 24:00. Monday must contain all 48 options, including 0000 and 2330. Change it to Monday 23:30 to 24:00. Only 2330 must remain.
  5. Test each user group that can create or edit listings. A user without field write permission must not gain it through the callback. Test an unrelated listing type without these fields too.

The normal JReviews listing, field, and option validation still applies. Whenever a form submits valid Opening hours, the customization replaces the selections in all seven weekday fields. It does not add them to the previous selections. If a form does not submit Opening hours, this conversion does not change the weekday fields.

Existing listings are not rebuilt automatically. Resave them through this form to create the search values. Imports, direct database writes, and other submission paths need a separate integration. These frontend hooks do not update those paths.

Learn more