How to add "Allowed Countries" field in custom form

To bring in the allowed countries field in your custom module config:

add the following to your module's system.xml

<sallowspecific translate="label">
    <label>Ship to Applicable Countries</label>
    <frontend_type>select</frontend_type>
    <sort_order>90</sort_order>
    <frontend_class>shipping-applicable-country</frontend_class>
    <source_model>adminhtml/system_config_source_shipping_allspecificcountries</source_model>
    <show_in_default>1</show_in_default>
    <show_in_website>1</show_in_website>
    <show_in_store>0</show_in_store>
</sallowspecific>
<specificcountry translate="label">
    <label>Ship to Specific Countries</label>
    <frontend_type>multiselect</frontend_type>
    <sort_order>91</sort_order>
    <source_model>adminhtml/system_config_source_country</source_model>
    <show_in_default>1</show_in_default>
    <show_in_website>1</show_in_website>
    <show_in_store>0</show_in_store>
    <can_be_empty>1</can_be_empty>
</specificcountry>

under <fields> tag in your custom section.

To add it in the admin form:

in app/code/local/Yourmodulename/Block/Adminhtml/Yourmodulename/Edit/Tab/Form.php

$countryList = Mage::getModel('directory/country')->getResourceCollection()->loadByStore()->toOptionArray(true);
$fieldset->addField('allowed_countries', 'multiselect', array( /* "allowed_countries" is the column name in your custom table to store these values */
    'name'      => 'countries[]',
    'label'     => Mage::helper('yourmodulename')->__('Allowed Countries'),
    'title'     => Mage::helper('yourmodulename')->__('Allowed Countries'),
    'required'  => true, /* only if it is required */
    'values'    => $countryList,
));

note:

  • You have to write logic to save the multiselect values in database in saveAction()

to display this in admin grid:

refer this link.


I found the solution.
To add a country multi select dropdown in your form you need to add below code in your Block/Adminhtml/ModuleName/Edit/Tab/Form.php file.

$countryList = Mage::getModel('directory/country')->getResourceCollection()->loadByStore()->toOptionArray(true);
$fieldset->addField('countries', 'multiselect', array(
            'name'      => 'countries[]',
            'label'     => Mage::helper('zones')->__('Countries'),
            'title'     => Mage::helper('zones')->__('Countries'),
            'required'  => true,
            'values'    => $countryList,
        ));

$fieldset->addField('country', 'select', array(  
        'name' => 'country',  
        'label' => 'Country',  
        'values' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),  
        ));