6

I need to add these 2 dropdowns to the contact form. How would I pull in those values for each dropdown?

2
  • You want to transfer State/Province dropdown and Country Dropdown from Checkout page to Contact form? Aug 3, 2016 at 16:21
  • Yes, I would like those as being required on the contact page.
    – Paul
    Aug 3, 2016 at 16:33

3 Answers 3

14

Following method will add Country and Region dropdown to contact us form,

[namespace]/[modulename]/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\Contact\Block\ContactForm" type="[namespace]\[modulename]\Block\ContactForm" />
</config>

[namespace]/[modulename]/Block/ContactForm

<?php

namespace [namespace]\[modulename]\Block;

use Magento\Framework\View\Element\Template;

class ContactForm extends \Magento\Contact\Block\ContactForm
{

    public function __construct(
            Template\Context $context,
            \Magento\Directory\Block\Data $directoryBlock, 
            array $data = []
    )
    {
        parent::__construct($context, $data);
        $this->_isScopePrivate = true;
        $this->directoryBlock = $directoryBlock;
    }

    public function getCountries()
    {
        $country = $this->directoryBlock->getCountryHtmlSelect();
        return $country;
    }
    public function getRegion()
    {
        $region = $this->directoryBlock->getRegionHtmlSelect();
        return $region;
    }
}

[namespace]/[modulename]/view/frontend/templates/form.phtml

<?php
$countryList=$block->getCountries();
$regionList=$block->getRegion();
?>
<div class="field country">
    <label class="label" for="country"><span><?php echo __('Country') ?></span></label>
    <div class="control">
        <?php echo $countryList?>
    </div>
</div>
<div class="field country">
    <label class="label" for="region"><span><?php  echo __('Region') ?></span></label>
    <div class="control">
        <?php echo $regionList?>
    </div>
</div>

Additional

So here is the further information for you to fetch region based on selected country

In you JS

$(document).on('change','#country',function() {
    var param = 'country='+$('#country').val();
    $.ajax({
        showLoader: true,
        url: YOUR_URL_HERE,
        data: param,
        type: "GET",
        dataType: 'json'
    }).done(function (data) {
        //data.value has the array of regions
    });
});

In your controller

public function __construct(
        Context       $context,
        \Magento\Framework\Controller\Result\JsonFactory    $resultJsonFactory,
        \Magento\Directory\Model\RegionFactory $regionColFactory,
        PageFactory $resultPageFactory
    ) {        
        $this->regionColFactory     = $regionColFactory;
        $this->resultJsonFactory            = $resultJsonFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();

        $result                 = $this->resultJsonFactory->create();
        $regions=$this->regionColFactory->create()->getCollection()->addFieldToFilter('country_id',$this->getRequest()->getParam('country'));
        return $result->setData(['success' => true,'value'=>$regions->getData()]);

    }

If you need any further help for ajax and data to be presented in phtml file please refer to this answer

7
  • How can we make the region value dependent based on country. Aug 4, 2016 at 4:01
  • 1
    fire ajax command and pass selected value of country dropdown as parameter then fetch records from directory_country_region according to selected country
    – Ekta Puri
    Aug 4, 2016 at 4:16
  • there are some predefined function in Magento/Directory/Model/Region.php you can use those to fetch region by country code, even have a look at Magento/Directory/Model/ResourceModel/Region.php
    – Ekta Puri
    Aug 4, 2016 at 4:46
  • @krishnaijjada I have updated answer which further informs how to have ajax call to fetch region based on selected country. Hope that helps
    – Ekta Puri
    Aug 4, 2016 at 5:24
  • Clear answer + 1, Out of curiosity in customer address edit file we can find script at the end. Doe't it help full ? ..:) vendor\magento\module-customer\view\frontend\templates\address\edit.phtml Aug 4, 2016 at 5:33
1
    In Phtml
    <div class="field company required">
                <label class="label" for="company"><span><?php echo __('Company') ?></span></label>
                <div class="control">
                    <input name="company" id="company" title="<?php echo __('company') ?>" value="" class="input-text letters-only" type="text" data-validate="{required:true,'letters-only':true}" style="width:400px"/>
                </div>
            </div>

            <div class="field country required">
                <label class="label" for="country"><span><?php echo __('Country') ?></span></label>
                <div class="control">
                   <?php echo $countryList?>
                </div>
            </div>


            <div class="field region required">
                <label class="label" for="region"><span><?php /* @escapeNotVerified */ echo __('State/Province') ?></span></label>
                <div class="control">
                    <?php echo $regionList?>
                </div>
            </div>
<script>
    require(["jquery"], function ($) {
$(document).on('change','#country',function() {
            //alert($('#country').val());
            if(document.getElementById('states')){
                document.getElementById('states').value = '';
            }
            if(document.getElementById('state')){
                document.getElementById('state').value = '';
            }
             var param = 'country='+$('#country').val();
             $.ajax({
                     showLoader: true,
                     url: '<?php /* @escapeNotVerified */ echo $block->getCatalogrequest(); ?>',
                     data: param,
                     type: "GET",
                     dataType: 'json'
             }).done(function (data) {

                 if(data.value=='')
                 {
                     $('.field.states.required').show();
                     $('.field.region.required').hide();
                 }
                 else
                 {
                    $('.field.states.required').hide();
                    $('.field.region.required').show();
                    $('#state').empty().append(data.value);
                 }
            });
    });
    });
</script>
0

You don't need AJAX for that. Just look at the customer add/edit address form.

template: vendor/magento/module-customer/view/frontend/templates/address/edit.phtml

block: vendor/magento/module-customer/Block/Address/Edit.php

Keep the only fields and methods you need in your custom template and block class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.