Skip to content

Commit f301d65

Browse files
authored
Update form_helper.php
Add form_fropdown_timezone() that supports all form_fropdown() parameters. timezone_select() in date_helper.php is too limited. Cannot specify field name or extra attributes limiting for backwards compatibility, maybe make timezone_select an alias/pass-through 🤷‍♂️
1 parent 686e9ae commit f301d65

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

system/Helpers/form_helper.php

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,61 @@ function form_multiselect($name = '', array $options = [], array $selected = [],
256256
}
257257
}
258258

259+
if (! function_exists('form_dropdown_timezone')) {
260+
/**
261+
* Timezone Drop-down Menu
262+
*
263+
* @param array|string $data
264+
* @param array|string $selected
265+
* @param array|object|string $extra string, array, object that can be cast to array
266+
* @param int|null $timezoneGroup DateTimeZone class constants
267+
* @param string|null $countryCode ISO 3166-1 compatible country code
268+
* @param bool $showOffset Whether to show UTC offset or not
269+
*/
270+
function form_dropdown_timezone($data = '', $selected = [], $extra = '', $useOptgroups = true, ?int $timezoneGroup = null, ?string $countryCode = null, bool $showOffset = true): string {
271+
if (!$timezoneGroup) {
272+
$timezoneGroup = ($countryCode) ? DateTimeZone::PER_COUNTRY : DateTimeZone::ALL;
273+
}
274+
275+
if ($countryCode && $timezoneGroup !== DateTimeZone::PER_COUNTRY) {
276+
throw new InvalidArgumentException('$timezoneGroup must be DateTimeZone::PER_COUNTRY when specifying $countryCode');
277+
}
278+
279+
if ($showOffset) {
280+
$datetime = new DateTime();
281+
}
282+
283+
$options = [];
284+
285+
foreach (DateTimeZone::listIdentifiers($timezoneGroup, $countryCode) as $identifier) {
286+
if ($useOptgroups) {
287+
list($group) = explode('/', $identifier);
288+
289+
$options[$group][$identifier] = substr($identifier, strlen($group) + 1) ?: $group;
290+
} else {
291+
$options[$identifier] = $identifier;
292+
}
293+
294+
if ($showOffset) {
295+
$datetime->setTimezone(new DateTimeZone($identifier));
296+
$seconds = $datetime->getOffset();
297+
$hours = intval($seconds / 3600);
298+
$minutes = abs(intval(($seconds % 3600) / 60));
299+
$formatted = sprintf(' (%+03d:%02d)', $hours, $minutes);
300+
301+
302+
if ($useOptgroups) {
303+
$options[$group][$identifier] .= $formatted;
304+
} else {
305+
$options[$identifier] .= $formatted;
306+
}
307+
}
308+
}
309+
310+
return form_dropdown($data, $options, $selected, $extra);
311+
}
312+
}
313+
259314
if (! function_exists('form_dropdown')) {
260315
/**
261316
* Drop-down Menu

0 commit comments

Comments
 (0)