I need to create dropdown boxes for country, state, and city in a web form, with the state dropdown depending on the selected country, and the city dropdown depending on the selected state. How can I achieve this?
Share and discuss the best content and new marketing ideas, build your professional profile and become a better marketer together.
I need to create dropdown boxes for country, state, and city in a web form, with the state dropdown depending on the selected country, and the city dropdown depending on the selected state. How can I achieve this?
Hi,
The following code retrieves the state based on the country_id. Similarly, you can obtain the city based on the state.
XML:
<template id="country_template" name="Country">
<t t-call="website.layout">
<div class="container">
<form class="form" id="create_form" method="post" action="/create/form">
<input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
<div class="row mb-3">
<label for="country_id" class="col-sm-2 col-form-label">Country</label>
<div class="col-sm-10">
<select id="country_id" name="country" class="form-control">
</select>
</div>
</div>
<div class="row mb-3">
<label for="state_id" class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select id="state_id" name="state" class="form-control">
</select>
</div>
</div>
</form>
</div>
</t>
</template>
.py:
class CountryData(Controller):
@route('/data', auth='public', website=True)
def form_data(self):
country_id = request.env['res.country'].sudo().search([])
return request.render('module_name.country_template', {'country_id': country_id})
@route('/create/form', auth='public', website=True)
def create_form(self, **kw):
form = request.env['model.name'].sudo().create({
'country_id': kw.get('country'),
'state_id': kw.get('state'),
'city_id': kw.get('city'),
})
return request.render('module_name.country_template', {'form': form})
@route('/get_states', type="json", auth='public', website=True)
def get_states(self, country_id):
states = request.env['res.country.state'].sudo().browse(int(country_id))
return states
JS:
publicWidget.registry.CountryData = publicWidget.Widget.extend({
selector: '#create_form',
events: {
'change #country_id': '_onCountryChange',
},
init: function (parent, options) {
this._super.apply(this, arguments);
this.rpc = this.bindService("rpc");
},
_onCountryChange: async function () {
var self = this
var country_id = this.$el.find('#country_id').val();
await jsonrpc("/get_states", {
country_id: country_id
}).then(function (records) {
self.$el.find('#state_id').empty();
self.$el.find('#state_id').prepend('<option value="">Select State</option>');
records.forEach(function (record) {
self.$('#state_id').append(
`<option value="${record.id}">${record.name}</option>`
);
});
});
},
})
Hope it helps.
Create an account today to enjoy exclusive features and engage with our awesome community!
Sign up