🧔 Hello World

My name is Emil. I am a programmer, passionate by coding, music, video and photography

Learning Concrete5 How To generate Country List for Select Form Element

Concrete5 Countries Helper works together with Zend Locale library.

In some cases, you'll need to generate in a custom Form this list because there is no Country Type in Form Block, when you add the input type field. It's possible to fill in the country dropdown selector with php code in combination with or without javascript code.

Version 1 of php country list generator using a foreach loop, looks like the following code:




$stateHelper = Loader::helper('lists/states_provinces');
$countryHelper = Loader::helper('lists/countries');
$states = $stateHelper->getStateProvinceArray('DE');
$countries = $countryHelper->getCountries();

foreach($countries as $abbr=>$fullName):
// your option code here
endforeach;



Version 2 looks like the code bellow:




$arCountries = array_merge(
array('' => t('Choose Country')),
Loader::helper('lists/countries')->getCountries()
);

$strSelectCountry = Loader::helper('form')->select(
'country', // name
$arCountries, // array created by getCountries()
'', // value selected, if comes from post var
array('style'=>'width: 100%') // css styles & tagAttributes
);

echo $strSelectCountry;



Special case of using countries List generated by javascript came when you want to override the original input/select element form that cames from C5 with custom list on jquery document ready status.



/*
// Here is an example of list conversion, from xml into js string, you can even use this from a json file
var arCountries = 'Afghanistan,Andorra,Angola,....'
var strCountries = ''...
*/

$(document).ready(function() {
// bPostFrm cames from $_POST php array and is set true or false
setTimeout(function(){

if(bPostFrm){
$selectHTML = '';
$oCountries = strCountries.split("");
$.each($oCountries, function(i,item){
if(i>0){
if(item.indexOf(sFrmSel)){
$selectHTML+= item.replace('value="'+sFrmSel+'"','value="'+sFrmSel+'" selected="selected"' ) + '';
}
else{
$selectHTML+= item + '';
}
}else{
$selectHTML+= item.replace('selected="selected"','') + '';
}
});
$('#QuestionC5').html($selectHTML);
}
else{
$('#QuestionC5').html(strCountries);
}
},800)
});



Other related articles:

Filtering a list of states based on selected country
http://www.concrete5.org/documentation/how-tos/developers/filtering-a-list-of-states-based-on-selected-country/

C5 Installing an Country Attribute Type
http://blog.david-reid.com/2012/09/06/c5-installing-an-attribute-type/

concrete5 Location Lists
http://www.concrete5.org/documentation/developers/helpers/location-lists

County in respect of Country list
http://www.concrete5.org/community/forums/usage/county-in-respect-of-country-list/

concrete5 Cheat Sheet
http://www.weblicating.com/doku/doku.php?id=cheatsheet/#.Up7sM8TuJMA