Please check this article ... Sorry, we can’t ship there. It should be exactly what you're looking for ...
Add a product attribute via installer to display countries as dropdown ...
/* @var $installer Mage_Eav_Model_Entity_Setup */
$installer = $this;
$installer->startSetup();
$installer->addAttribute(
Mage_Catalog_Model_Product::ENTITY,
'shipping_restriction',
array(
'type' => 'varchar',
'group' => 'General',
'input' => 'multiselect',
'label' => 'Disallow Shipping to',
'source' => 'inchoo_shippingrestriction/attribute_source_country',
'backend' => 'inchoo_shippingrestriction/attribute_backend_country',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_WEBSITE,
'apply_to' => 'simple,configurable,bundle,grouped',
'required' => false
)
);
$installer->endSetup();
Source model ...
class Inchoo_ShippingRestriction_Model_Attribute_Source_Country
extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
implements Mage_Eav_Model_Entity_Attribute_Source_Interface
{
/**
* Get list of all available countries
*
* @return array|mixed
*/
public function getAllOptions()
{
$cacheKey = 'DIRECTORY_COUNTRY_SELECT_STORE_' . Mage::app()->getStore()->getCode();
if (Mage::app()->useCache('config') && $cache = Mage::app()->loadCache($cacheKey)) {
$options = unserialize($cache);
} else {
$collection = Mage::getModel('directory/country')->getResourceCollection();
$options = $collection->toOptionArray();
if (Mage::app()->useCache('config')) {
Mage::app()->saveCache(serialize($options), $cacheKey, array('config'));
}
}
return $options;
}
}
Backend model
class Inchoo_ShippingRestriction_Model_Attribute_Backend_Country
extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
implements Mage_Eav_Model_Entity_Attribute_Backend_Interface
{
public function beforeSave($object)
{
$attrCode = $this->getAttribute()->getAttributeCode();
$object->setData($attrCode, implode(',', $object->getData($attrCode)));
return $this;
}
public function afterLoad($object)
{
$attrCode = $this->getAttribute()->getAttributeCode();
$object->setData($attrCode, explode(',', $object->getData($attrCode)));
return $this;
}
}
Shipping model
class Inchoo_ShippingRestriction_Model_Shipping extends Mage_Shipping_Model_Shipping
{
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
if ($this->isShippingRestriction($request)) {
return $this;
}
return parent::collectRates($request);
}
/**
* Check if shipping restrictions apply
*
* @param Mage_Shipping_Model_Rate_Request $request
* @return bool
*/
public function isShippingRestriction(Mage_Shipping_Model_Rate_Request $request)
{
$options = array();
/** @var Mage_Sales_Model_Quote_Item $quoteItem */
foreach ($request->getAllItems() as $quoteItem) {
$options = array_merge(
$options,
explode(',', $quoteItem->getProduct()->getShippingRestriction())
);
}
return in_array($request->getDestCountryId(), $options);
}
}