From f03cca4386a0f45a5c3aafdc7d6243157cd431fc Mon Sep 17 00:00:00 2001 From: Paul Chavard Date: Thu, 23 Jan 2020 14:12:19 +0000 Subject: [PATCH] Search departements by code --- app/javascript/new_design/select2.js | 14 +++++++++++++- app/javascript/shared/utils.js | 4 ++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/app/javascript/new_design/select2.js b/app/javascript/new_design/select2.js index 8de34648d..7a82b9115 100644 --- a/app/javascript/new_design/select2.js +++ b/app/javascript/new_design/select2.js @@ -1,5 +1,6 @@ import $ from 'jquery'; import 'select2'; +import { isNumeric } from '@utils'; const { api_geo_url, api_adresse_url } = gon.autocomplete || {}; @@ -80,10 +81,21 @@ const communesOptions = { const etranger99 = { id: '99 - Étranger', text: '99 - Étranger' }; const departementsOptions = { ...baseOptions, - minimumInputLength: 2, + minimumInputLength: 1, ajax: { ...baseAjaxOptions, url: `${api_geo_url}/departements`, + data({ term }) { + const data = { fields: 'nom,code' }; + + if (isNumeric(term)) { + data.code = term.trim().padStart(2, '0'); + } else { + data.nom = term; + } + + return data; + }, processResults(data) { return { results: data diff --git a/app/javascript/shared/utils.js b/app/javascript/shared/utils.js index 9be438b76..0921b6d68 100644 --- a/app/javascript/shared/utils.js +++ b/app/javascript/shared/utils.js @@ -78,6 +78,10 @@ export function to(promise) { return promise.then(result => [result]).catch(error => [null, error]); } +export function isNumeric(n) { + return !isNaN(parseFloat(n)) && isFinite(n); +} + function offset(element) { const rect = element.getBoundingClientRect(); return {