SilverStripe中CountryDropdownField
生成的下拉菜单的默认顺序是按字母顺序排列的:
如何订购下拉列表,以便常见国家位于列表的首位,然后按字母顺序列出较少使用的国家/地区?
即
答案 0 :(得分:4)
我们可以创建自己的国家/地区数组,并使用CountryDropdownField
setSource
功能设置国家/地区的顺序:
$countriesList = Zend_Locale::getTranslationList('territory', i18n::get_locale(), 2);
asort($countriesList, SORT_LOCALE_STRING);
$commonCountries = array(
'AU' => 'Australia',
'CA' => 'Canada',
'FR' => 'France',
'DE' => 'Germany',
'NZ' => 'New Zealand',
'ZA' => 'South Africa',
'GB' => 'United Kingdom',
'US' => 'United States'
);
CountryDropdownField::create('Country', 'Country')
->setSource(array_merge($commonCountries, $countriesList));
或者使用uksort
而不是合并数组:
$countriesList = Zend_Locale::getTranslationList('territory', i18n::get_locale(), 2);
$commonCountries = array('AU', 'CA', 'FR', 'DE', 'NZ', 'ZA', 'GB', 'US');
uksort($countriesList, function ($a, $b) use ($countriesList, $commonCountries) {
if (in_array($a, $commonCountries)) {
if (in_array($b, $firstCountries)) {
return ($countriesList[$a] < $countriesList[$b]) ? -1 : 1;
}
return -1;
}
if (in_array($b, $commonCountries)) {
return 1;
}
return ($countriesList[$a] < $countriesList[$b]) ? -1 : 1;
});
CountryDropdownField::create('Country', 'Country')->setSource($countriesList);