`
kirenenko04
  • 浏览: 152317 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

Add Country and Region To Custom model table Frontend & Backend Edit Form

 
阅读更多

Frontend:

 

you can see these form html elems: They are country_id, country, province, and province_id elems

 

 <div class="content-input">
        	<label>Region:</label>
        	<select id="province_id" name="province_id" title="<?php echo $this->__('State/Province/Region') ?>" class="validate-select" style="display:none;">
                           <option value=""><?php echo $this->__('Please select region, state or province') ?></option>
             </select>
             <input type="text" id="province" name="province" value=""  title="<?php echo $this->__('State/Province') ?>" class="input-text <?php echo $this->helper('customer/address')->getAttributeValidationClass('region') ?>" />
              <script type="text/javascript">
                        //<![CDATA[
                            $('province_id').setAttribute('defaultValue',  "<?php echo $array['province_id'];
                             ?>");
                        //]]>
                  </script>
        </div>
        <div class="content-select ">
            <label><em>*</em> Country :</label>
             <?php echo $this->getCountryHtmlSelect($array['country_id']) ?>
             <input type="text" id="country" name="country" value="<?php echo $array['country'];?>"  title="<?php echo $this->__('Country') ?>" class="input-text <?php echo $this->helper('customer/address')->getAttributeValidationClass('country') ?>" />
        </div>
       <div class="content-input">
            <label>Postcode :</label>
            <input type="text" id="postcode" name="postcode" size=50 maxlength="20" value="<?php echo $this->escapeHtml ( $array ['postcode'] );?>" />
       </div>

 

And than add these js function (Magento core function) . make the COUNTRY-REGION works

<script type="text/javascript">
//<![CDATA[
    var dataForm = new VarienForm('form-validate', true);
    new RegionUpdater('country', 'province', 'province_id', <?php echo $this->helper('directory')->getRegionJson() ?>, undefined, '');    //]]>

    (function($){  
        $('#province_id').change(function(){
            $('#province').val($("#province_id option:selected").html());
        })
         $("input[name='country']").hide();
    })(jQuery); 
 </script>

 

In Php controller file,

 you can set country by country_id

and set province by province_id

 

// get country name
 $params['country'] = Mage::app()->getLocale()->getCountryTranslation(trim($params['country_id']));

//get region code
$regionModel = Mage::getModel('directory/region')->load((int)$params['province_id']);
$params['province'] = $regionModel->getCode();				
	           

 

Backend: 

1. set custom template for adminhtml grid file . 

public function __construct()
	{
		parent::__construct();
		$this->setTemplate('mymap/tab/form.phtml');
	}

 

 2.Then, add country_id, province_id elem to grid files:

 

 

<?php

class Bysoft_Mymap_Block_Adminhtml_Mymap_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
	public function __construct()
	{
		parent::__construct();
		$this->setTemplate('mymap/tab/form.phtml');
	}
	
	public function getRegionsUrl()
	{
		return $this->getUrl('*/json/countryRegion');
	}
	
	public function getDefaultCountryId() {
		$editOradd = Mage::registry('mymap_data') && Mage::registry('mymap_data')->getId();
		
		if ($editOradd) {
			return Mage::registry('mymap_data')->getCountryId();
		} else return 0;
	}
	
	public function getDefaultProvinceId() {
		$editOradd = Mage::registry('mymap_data') && Mage::registry('mymap_data')->getId();
		if ($editOradd) {
			return Mage::registry('mymap_data')->getProvinceId();
		} else return 0;
	}
	
	
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form();
        $this->setForm($form);
        $fieldset = $form->addFieldset('mymap_form', array('legend'=>Mage::helper('mymap')->__('Item information')));
        
        $editOradd = Mage::registry('mymap_data') && Mage::registry('mymap_data')->getId();
        if (!$editOradd) {
            $values = array(array('value' => '2','label' => 'rep'));
        } else {
            if (Mage::registry('mymap_data')->getType() == '1') {
                $values = array(array('value' => '1','label' => 'store',));
            } else {
                $values = array(array('value' => '2','label' => 'rep',));
            }
        }
        $fieldset->addField('type', 'select', array(
            'label'     => Mage::helper('mymap')->__('Type'),
            'class'     => 'required-entry',
            'required'  => true,
            'name'      => 'type',
            'values'    => $values,
        ));
        
        $fieldset->addField('customer_id', 'text', array(
            'label'     => Mage::helper('mymap')->__('Customer Id'),
            'required'  => false,
            'name'      => 'customer_id',
        ));
        
        $fieldset->addField('email', 'text', array(
            'label'     => Mage::helper('mymap')->__('Email'),
            'class'     => 'validate-email',
            'required'  => false,
            'name'      => 'email',
        ));
        
        $fieldset->addField('title', 'text', array(
            'label'     => Mage::helper('mymap')->__('Store/Rep Name'),
            'name'      => 'title',
        ));
        
        $fieldset->addField('phone', 'text', array(
            'label'     => Mage::helper('mymap')->__('Phone'),
            'name'      => 'phone',
        ));

         
         $fieldset->addField('city', 'text', array(
         		'label'     => Mage::helper('mymap')->__('City'),
         		'class'     => 'required-entry',
         		'required'  => true,
         		'name'      => 'city',
         ));
         
         $fieldset->addField('address', 'text', array(
         		'label'     => Mage::helper('mymap')->__('Address'),
         		'class'     => 'required-entry',
         		'required'  => true,
         		'name'      => 'address',
         ));
         
         $fieldset->addField('postcode', 'text', array(
         		'label'     => Mage::helper('mymap')->__('Postcode'),
         		'required'  => false,
         		'name'      => 'postcode',
         ));
          
         $fieldset->addField('address_hide', 'text', array(
         		'label'     => Mage::helper('mymap')->__('Coordinate'),
         		// 'class'     => 'required-entry',
         		'required'  => false,
         		'name'      => 'address_hide',
         ));
        
         $fieldset->addField('country_id', 'select', array(
         		'name'  => 'country_id',
         		'label'     => 'Country',
         		'required' => true,
         		'class'    => 'countries',
        	    'values'   => array(
        	    		array(
        	    				'value'  => '',
        	    				'label'  => '',
        	    		),
        	    		array(
        	    				'value'  => 'CA',
        	    				'label'  => 'Canada',
        	    		),
        	    		array(
        	    				'value'  => 'MX',
        	    				'label'  => 'Mexico',
        	    		),
        	    		array(
        	    				'value'  => 'US',
        	    				'label'  => 'United States',
        	    		),
         			),
         ));
        
         /*
        $fieldset->addField('country', 'text', array(
        		'label'     => Mage::helper('mymap')->__('Country'),
        		// 'class'     => 'required-entry',
        		'required'  => false,
        		'name'      => 'country',
        ));
        */
        
        
        $fieldset->addField('province_id', 'select', array(
        		'label'     => Mage::helper('mymap')->__('Province'),
        		'class'     => 'required-entry',
        		'required'  => false,
        		'name'      => 'province_id',
        ));
        
        /*
        $fieldset->addField('province', 'text', array(
        		'label'     => Mage::helper('mymap')->__('Province'),
        		// 'class'     => 'required-entry',
        		'required'  => false,
        		'name'      => 'province'
        ));
        */
        
        $fieldset->addField('allow_show', 'select', array(
            'label'     => Mage::helper('mymap')->__('Allow Show'),
            'class'     => 'required-entry',
            'required'  => true,
            'name'      => 'allow_show',
            'values'    => array(
                array(
                    'value'  => '1',
                    'label'  => 'Yes',
                ),
                array(
                    'value'  => '0',
                    'label'  => 'No',
                ),
            ),
        ));
        
        $fieldset->addField('status', 'select', array(
            'label'     => Mage::helper('mymap')->__('Status'),
            'name'      => 'status',
            'values'    => array(
                array(
                    'value'     => Bysoft_Mymap_Model_Status::STATUS_ACTIVE,
                    'label'     => Mage::helper('mymap')->__('Active'),
                ),
                array(
                    'value'     => Bysoft_Mymap_Model_Status::STATUS_DESACTIVE,
                    'label'     => Mage::helper('mymap')->__('Desactive'),
                ),
                array(
                    'value'     => Bysoft_Mymap_Model_Status::STATUS_DELETED,
                    'label'     => Mage::helper('mymap')->__('Deleted'),
                ),
            ),
        ));

        $formData = '';
        $session = Mage::getSingleton('adminhtml/session');
        
        if ($session->getMymapData()) {
            $formData = $session->getMymapData();
            $session->setMymapData(null);
        } elseif ( Mage::registry('mymap_data') ) {
            $formData = Mage::registry('mymap_data')->getData();
        }
        
        if (isset($formData['inside_picture']) && $formData['inside_picture'] != '') {
            $fieldset->addField('labelImage', 'label', array(
                'label' => $this->__('Inside Picture'),
                'after_element_html' => '<img width="400" src="' . dirname(Mage::getUrl()) . '/' . $formData['inside_picture'] . '"/>'
            ));
        }
        
        if (isset($formData['outside_picture']) && $formData['outside_picture'] != '') {
            $fieldset->addField('labelImage2', 'label', array(
                'label' => $this->__('Outside Picture'),
                'after_element_html' => '<img width="400" src="' . dirname(Mage::getUrl()) . '/' . $formData['outside_picture'] . '"/>'
            ));
        }
        
        if (!empty($formData)) {
            $form->setValues($formData);
        }
        
        return parent::_prepareForm();
    }
    
    public function getDefaultCountriesJson()
    {
    	$websites = Mage::getSingleton('adminhtml/system_store')->getWebsiteValuesForForm(false, true);
    	$result = array();
    	foreach ($websites as $website) {
    		$result[$website['value']] = Mage::app()->getWebsite($website['value'])->getConfig(
    				Mage_Core_Helper_Data::XML_PATH_DEFAULT_COUNTRY
    		);
    	}
    	return Mage::helper('core')->jsonEncode($result);
    }
    
    public function getCountryCollection()
    {
    	$collection = $this->getData('country_collection');
    	if (is_null($collection)) {
    		$collection = Mage::getModel('directory/country')->getResourceCollection()
    		->loadByStore();
    		$this->setData('country_collection', $collection);
    	}
    
    	return $collection;
    }
    

    public function getCountryHtmlSelect($defValue=null, $name='country_id', $id='country', $title='Country')
    {
    	Varien_Profiler::start('TEST: '.__METHOD__);
    	if (is_null($defValue)) {
    		$defValue = $this->getCountryId();
    	}
    	$cacheKey = 'DIRECTORY_COUNTRY_SELECT_STORE_'.Mage::app()->getStore()->getCode();
    	if (Mage::app()->useCache('config') && $cache = Mage::app()->loadCache($cacheKey)) {
    		$options = unserialize($cache);
    	} else {
    		$options = $this->getCountryCollection()->toOptionArray();
    		if (Mage::app()->useCache('config')) {
    			Mage::app()->saveCache(serialize($options), $cacheKey, array('config'));
    		}
    	}
    	$html = $this->getLayout()->createBlock('core/html_select')
    	->setName($name)
    	->setId($id)
    	->setTitle(Mage::helper('directory')->__($title))
    	->setClass('validate-select')
    	->setValue($defValue)
    	->setOptions($options)
    	->getHtml();
    
    	Varien_Profiler::stop('TEST: '.__METHOD__);
    	return $html;
    }
}

 

3.create custom teplate file and add ajax for it:


<?php
echo $this->getForm()->getHtml();
$id = Mage::app()->getRequest()->getParam('id');
$obj = Mage::getModel('mymap/locator')->load($id);
if ($obj) {
	$province_id = $obj->getData('province_id');
} else {
	$province_id = 0;
}
?>
<script type="text/javascript">
//<![CDATA[

(function($){  
	
    var province_id = '<?php echo $province_id;?>';
	$("#country_id").live('change',function(){
		var country_id = $("#country_id").val();
		$("#province_id option").remove(); 
		$("#province_id").append('<option value=""></option>');
		$.ajax({    
	        url: "<?php echo $this->getUrl('mymap/index/getregionsadmin');?>",    
	        type: "POST",    
	        data:{country_id:country_id,province_id:province_id},
	        dataType:"json", 
	        success: function(data) {       
	        	 $.each( data, function(index, content){ 
		        	if (content.selected == '1') {
		        		var option_html = "<option selected='selected' value='"+content.value+"'>" + content.default_name+"</option>";        			
			        } else {
		        		var option_html = "<option value='"+content.value+"'>" + content.default_name+"</option>";
			        }
		        	$("#province_id").append(option_html);
		        });
	        }    
	    }); 
	})
	$("#country_id").change();
})(jQuery); 
//]]>
</script>

 

4.create custom function for get Region list by country id

	public function getregionsadminAction() {
    	$country_id = $_REQUEST['country_id'];
    	$province_id = $_REQUEST['province_id'];
    	$html = array();
    	if ($country_id) {
    		$collection = Mage::getModel('directory/region')->getResourceCollection()
    		->addCountryFilter($country_id)
    		->load();    		
    		foreach ($collection as $region) {
    			$data = array();
    			if ($province_id == $region->getId()) {
    				$data['selected'] = 1; 				
    			} else {
    				$data['selected'] = 0;		
    			}
    			$data['value'] = $region->getId();
    			$data['default_name'] = $region->getData('default_name');
    			
    			$html[] = $data;
    		}
    	}
    	
    	echo json_encode($html);
    }

 

 

分享到:
评论

相关推荐

    Full-Stack Vue.js 2 and Laravel 5 Bring the frontend and backend together epub

    Full-Stack Vue.js 2 and Laravel 5 Bring the frontend and backend together with Vue, Vuex, and Laravel 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网...

    FrontEnd&jad;

    而"FrontEnd&jad;"这个主题似乎关联到前端开发领域,并且与Java反编译工具有关,这对于理解、学习和分析Java代码非常有用。下面我们将详细探讨这些知识点。 首先,前端开发主要涉及HTML、CSS和JavaScript技术,它们...

    杨凯-Backend For Frontend(BFF)in Serverless.pdf

    杨凯-Backend For Frontend(BFF)in Serverless.pdf 杨凯-Backend For Frontend(BFF)in Serverless.pdf 杨凯-Backend For Frontend(BFF)in Serverless.pdf

    Frontend Architecture for Design Systems

    Imagine what a large-scale web project would look like if frontend development were not treated as an add-on, but as an equal partner with backend development and content strategy. This practical book...

    pdocrud.rar

    You can use PDOCrud to generate both frontend and backend of your application. By writing just 2-3 lines of code only, you can perform insert/update/delete and select operation. You just to need to ...

    MT-Project-Seed:网络建设的种子项目

    MT.Project.seed Node项目模板/前端自动构建 Before ...├── backend │ ├── app_run.json # 运行环境 │ └── enum_env.json # 运行环境枚举 ├── frontend │ ├── bower.json # 包管理

    EmployeeManagement_FrontEnd-BackEnd

    本项目“EmployeeManagement_FrontEnd-BackEnd”则是一个完整的前端与后端解决方案,主要采用了Vue技术栈进行构建。接下来,我们将深入探讨其中的关键技术和实现方式。 首先,前端部分基于Vue.js框架,Vue作为一款...

    frontend-backend-sample:Node.js和javascript使用的后端和前端项目

    后端前端样本本地运行git clone https://github.com/tafrishy/frontend-backend-sample.git # or clone your own forkcd frontend-backend-samplenpm installnpm start 您的应用程序现在应该在上运行。

    Azure实战.英文版.Azure.in.Action.Chris.Hay.Brian.H.Prince.高清文字版

    Then, it explores designing and scaling frontend and backend services that run in the cloud. Through clear, crisp examples, you'll discover all facets of Azure, including the development fabric, web ...

    ASP.NET Core 3 and React.pdf

    You'll then cover important .NET Core features such as API controllers, attribute routing, and model binding to help you build a sturdy backend. Additionally, you'll explore API security with ASP.NET...

    Learning GraphQL--2018

    Create a schema for a PhotoShare application that serves as a roadmap and a contract between the frontend and backend teams Use JavaScript to build a fully functioning GraphQL service and Apollo to ...

    ZSTechnology_Laravel:具有Frontend和Backend的真实公司的网站。 具有员工管理系统

    关于Laravel Laravel是一个具有表达力,优雅语法的Web应用程序框架。 我们认为,发展必须是一种令人愉快的,富有创造力的经历,才能真正实现。 Laravel减轻了许多Web项目中使用的常见任务,从而减轻了开发过程中的...

    OpenCart Theme and Module Development

    you will learn to create customized pages for feedback management and make an admin section where you will make forms and lists to perform CRUD functionalities and show this feedback at the frontend.

    frontend-backend-study:学习综合使用前预测知识开发软件

    这个名为"frontend-backend-study"的学习资源包,显然旨在帮助开发者掌握从前端到后端的全方位技能,以实现软件开发的综合能力。让我们详细探讨一下这个学习路径中涉及的技术和知识点。 首先,我们从前端开发开始,...

    OpenCartThemingandModuleDevelopment.pdf 英文原版

    you will learn to create customized pages for feedback management and make an admin section where you will make forms and lists to perform CRUD functionalities and show this feedback at the frontend.

    Trainable Frontend For Robust and Far-Field Keyword Spotting.pdf

    Trainable Frontend For Robust and Far-Field Keyword Spotting 1. Introduction 2. Per-Channel Energy Normalization 3. Trainable PCEN Fronten 4. Experiments: PCEN vs. log-mel 5. Discussions and ...

    Yii2隐藏frontend/web和backend/web的方法

    在Yii2的项目结构中,通常会有frontend/web和backend/web这两个目录,分别用于存放前端和后端的Web资源文件。但在一些生产环境下,为了安全起见,我们可能会希望隐藏这两个目录,不被外界直接访问。 隐藏frontend/...

    five-level-frontend

    API-DB苹果git clone frontend && git clone api && git clone fullstack-template && cd fullstack-template && bin /运行视窗git clone frontend && git clone api && git clone fullstack-template && cd ful

Global site tag (gtag.js) - Google Analytics