summaryrefslogtreecommitdiff
path: root/src/components/forms/address_form.tsx
blob: 2d3b8f48ae5744f0e0b7caf65507aea2fe8236b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Form } from "react-router-dom";
import countryList from "react-select-country-list";
import FieldProperties from "./fields/field_properties";
import Field from "./fields/field";
import SelectField from "./fields/select_field";
import { setFieldErrorMessages } from "../../lib/form_utils";

function getFieldProperties(address?: any) {
  const fields: Array<FieldProperties> = [
    {
      id: "street-field",
      type: "text",
      name: "street",
      label: "Calle",
      placeholder: address?.street
    },
    {
      id: "number-field",
      type: "number",
      name: "number",
      label: "Número",
      placeholder: address?.number
    },
    {
      id: "zip-code-field",
      type: "number",
      name: "zip_code",
      label: "Código postal",
      placeholder: address?.zip_code
    },
    {
      id: "city-field",
      type: "text",
      name: "city",
      label: "Ciudad",
      placeholder: address?.city
    }
  ];

  return fields;
}

function getCountrySelectOptions(address: any, country_code: string) {
  if(address && country_code == address.country)
    return (<option key={ country_code } value={ country_code } selected>{ countryList().getLabel(country_code) }</option>);
  else
    return (<option key={ country_code } value={ country_code }>{ countryList().getLabel(country_code) }</option>);
}


export default function AddressForm({ address = null, errors = null }) {
  let field_properties = getFieldProperties(address);
  const select_field_properties: FieldProperties = {
    id: "country-field",
    type: "select",
    name: "country",
    label: "País"
  }

  if(errors)
    field_properties = setFieldErrorMessages(field_properties, errors);
  
  const options = countryList().getValues().map(country_code => 
    getCountrySelectOptions(address, country_code)
  );

  const fields = field_properties.map(field_property =>
    <Field properties={field_property}/>
  );

  return(
    <Form method="post" id="address-form">
      {fields}
      <SelectField properties={select_field_properties} options={options}/>
      <button type="submit" className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Enviar</button>
    </Form>
  );
}