react-bootstrap#FormGroup JavaScript Examples

The following examples show how to use react-bootstrap#FormGroup. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: examples.js    From create-sas-app with Apache License 2.0 6 votes vote down vote up
createNewFolderExample = props => {
	return <div>
		<h5 className={'mb-0'}>Create new folder</h5>
		<div>To create folder we need URI of parent folder</div>
		<div>For this example we'll use metadataRoot folder's details above</div>
		<code>createNewFolder(parentUri, folderName, options)</code>
		<div>
			<label className={'mr-2'}>parentFolderUri:</label><span className={'comment'}>{props.state.folderDetails ?
			Utils.getSelfUri(props.state.folderDetails.links) :
			<Button
				bsstyle={'btn-sm btn-primary mr-2'}
				onClick={props.getFolderDetails}>Get
			</Button>}</span>
		</div>
		<Row className={'mt-3'}>
			<Col md={5}>
				<FormGroup>
					<FormControl
						type={'text'}
						placeholder={'folderName'}
						value={props.state.newFolder}
						onChange={e => props.setState({newFolder: e.target.value})}
					/>
				</FormGroup>
			</Col>
			<Col md={2}>
				<Button
					bsstyle={'btn btn-primary mr-2 btn-loading'}
					onClick={props.createNewFolder}
					disabled={!props.state.folderDetails || !props.state.newFolder || props.state.creatingNewFolder}
				>
					{props.state.creatingNewFolder && <i className={'fas fa-spinner fa-spin'}/>} Create
				</Button>
			</Col>
		</Row>
		<hr/>
	</div>
}
Example #2
Source File: LoginForm.js    From aws-workshop-colony with Apache License 2.0 6 votes vote down vote up
render() {
    return (
      <Navbar.Form>
        <Form onSubmit={this.handleSubmit}>
          <FormGroup style={formGroupStyle}>
            <FormControl
              type="text"
              name="email"
              placeholder="Email"
              onChange={this.handleInputChange}
            />
            <FormControl
              type="password"
              name="password"
              placeholder="Password"
              onChange={this.handleInputChange}
              style={passwordStyle}
            />
            <Button type="submit" bsStyle="success" style={logInButtonStyle}>
              LOGIN
            </Button>
          </FormGroup>
        </Form>
      </Navbar.Form>
    );
  }
Example #3
Source File: FieldGroup.js    From aws-workshop-colony with Apache License 2.0 6 votes vote down vote up
FieldGroup = ({ id, label, help, error, ...props }) => {
    return (
        <FormGroup controlId={id} validationState={error ? 'error' : null}>
            <ControlLabel>{label}</ControlLabel>
            <FormControl {...props} />
            {help && <HelpBlock>{help}</HelpBlock>}
            {error && <div className="alert alert-danger">{error}</div>}
        </FormGroup>
    );
}
Example #4
Source File: SelectFieldGroup.js    From aws-workshop-colony with Apache License 2.0 6 votes vote down vote up
SelectFieldGroup = ({ id, label, options, help, error, ...props }) => {
    return (
        <FormGroup controlId={id} validationState={error ? 'error' : null}>
            <ControlLabel>{label}</ControlLabel>
            <FormControl componentClass="select"  {...props}>
                {options.map(option=>{
                    return <option key={option.value} value={option.value}>{option.text}</option>;
                })}
            </FormControl>
            {help && <HelpBlock>{help}</HelpBlock>}
            {error && <div className="alert alert-danger">{error}</div>}
        </FormGroup>
    );
}
Example #5
Source File: BundleInformationModal.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 5 votes vote down vote up
export default function BundleInformationModal({ show, parcelle, onClose }) {
    const [loading, setLoading] = useState(false);
    const [format, setFormat ] = useState("pdf");
    const [letters, setLetters] = useState([]);
    const [firstOpen, setFirstOpen] = useState(false);
    useEffect(() => {
        if (show && parcelle) {
            setFirstOpen(false);
            getBatimentsByParcelle({parcelle}).then(data => setLetters(data));
        }
    }, [show, parcelle]);
    const [letter, setLetter] = useState();
    useEffect(() => {
        if (letters.length > 0 && !firstOpen) {
            setFirstOpen(true);
            setLetter(letters[0].dnubat);
        }
    }, [letters]);
    return (<Modal
        style={{ maxHeight: "100%", overflowY: "auto", zIndex: 10000 }}
        dialogClassName="cadastrapp-modal"
        show={show}
        onHide={onClose}>
        <Modal.Header closeButton>
            <Modal.Title><Message msgId={'cadastrapp.lots.title'}/> { parcelle }</Modal.Title>
        </Modal.Header>
        <Modal.Body>
            <div><Message msgId={'cadastrapp.lots.batiments'}/></div>
            {letters.map(({ dnubat }) => <Button bsStyle={letter === dnubat ? "primary" : undefined} onClick={() => setLetter(dnubat)}>{dnubat}</Button>)}
        </Modal.Body>
        <FormGroup>
            <b style={{ "float": "left", width: 150, marginRight: 15 }}><Message msgId={'cadastrapp.lots.type.title'}/>:</b>
            <Radio checked={format === 'pdf'} value="pdf" onChange={() => setFormat("pdf")} inline>
                <Message msgId={'cadastrapp.lots.type.pdf'}/>
            </Radio>
            <Radio checked={format === 'csv'} value="csv" onChange={() => setFormat("csv")} inline>
                <Message msgId={'cadastrapp.lots.type.csv'}/>
            </Radio>
        </FormGroup>
        <Modal.Footer>
            <Button
                disabled={loading}
                bsStyle="primary"
                onClick={() => {
                    setLoading(true);
                    (format === "csv" ? exportLotsAsCSV({ parcelle, dnubat: letter }) : exportLotsAsPDF({ parcelle, dnubat: letter }))
                        .then(response => {
                            downloadResponse(response);
                            setLoading(false);
                        })
                        .catch(() => {
                            setLoading(false);
                        });
                }}
            >
                {loading ? <Spinner spinnerName="circle" noFadeIn overrideSpinnerClassName="spinner" /> : null} Export</Button>
        </Modal.Footer>
    </Modal>);
}
Example #6
Source File: Login.js    From create-sas-app with Apache License 2.0 5 votes vote down vote up
render() {
		return (
			<div className="login">
				<div className="flex justify-content-center align-items-center">
					<Card className={'w100 mb0'}>
						<Row className="loginForm">
							<Col md={12}>
								<Form noValidate validated={this.state.validated}>
									<h1>Login</h1>
									<p className="text-muted">Sign In to your account</p>
									<FormGroup>
										<InputGroup>
											<InputGroup.Prepend><i className={'fas fa-user'}/></InputGroup.Prepend>
											<Form.Control
												name={'username'}
												className={`textInput`}
												placeholder={'Username'}
												value={this.state.username}
												onChange={this.onInputChange}
												required
											/>
										</InputGroup>
									</FormGroup>
									<FormGroup>
										<InputGroup>
											<InputGroup.Prepend><i className={'fas fa-lock'}/></InputGroup.Prepend>
											<Form.Control
												name={'password'}
												placeholder={'Password'}
												type={'password'}
												value={this.state.password}
												onChange={this.onInputChange}
												required
											/>
										</InputGroup>
									</FormGroup>
									<Row>
										<Col md={12}>
											<Button
												onClick={this.login}
												bsstyle={'primary'}
												disabled={this.validateEmail() === 'error' || this.validatePassword() === 'error' || !this.state.username || !this.state.password}
												className={'pull-right'}
											>Login</Button>
											{this.state.error && <div className={'text-danger'}>{this.state.error}</div>}
										</Col>
									</Row>
								</Form>
							</Col>
						</Row>
					</Card>
				</div>
			</div>
		);
	}
Example #7
Source File: BuildingButtons.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 5 votes vote down vote up
// select options to download full bundle
function BundleRadio({ show, dnubat, parcelle}) {
    let className = show ? "" : "collapse";
    const [format, setFormat] = useState('pdf');
    const [loading, setLoading] = useState(false);
    return (
        <div className={className}>
            <hr></hr>
            <div
                style={{ width: "70%" }}
                className="pull-left">
                <FormGroup>
                    <b style={{ "float": "left", width: 150, marginRight: 15 }}><Message msgId={'cadastrapp.lots.type.title'}/>:</b>
                    <Radio checked={format === 'pdf'} value="pdf" onChange={() => setFormat("pdf")} inline>
                        <Message msgId={'cadastrapp.lots.type.pdf'}/>
                    </Radio>
                    <Radio checked={format === 'csv'} value="csv" onChange={() => setFormat("csv")} inline>
                        <Message msgId={'cadastrapp.lots.type.csv'}/>
                    </Radio>
                </FormGroup>
            </div>
            <div
                style={{ width: "30%" }}
                className="pull-left">
                <Button
                    disabled={loading}
                    onClick={() => {
                        setLoading(true);
                        const handler = format === 'csv' ? exportLotsAsCSV : exportLotsAsPDF;
                        handler({
                            dnubat,
                            parcelle
                        }).then((response) => {
                            setLoading(false);
                            downloadResponse(response);
                        }).catch(() => {
                            setLoading(false); // TODO: handle error
                        });
                    }}
                    className="pull-right">
                    {loading ? <Spinner spinnerName="circle" noFadeIn overrideSpinnerClassName="spinner" /> : null}
                    Export
                </Button>
            </div>
            <hr></hr>
        </div>);
}
Example #8
Source File: PropertiesRadio.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 5 votes vote down vote up
export default function PropertiesRadio({
    showParcelle = true,
    expanded,
    parcelle,
    data = [],
    selected = []
}) {

    let className = expanded ? "" : "collapse";
    const [useParcelle, setUseParcelle] = useState(showParcelle);
    const [format, setFormat] = useState('pdf');
    const [loading, setLoading] = useState(false);

    return (
        <div className={className}>
            <hr/>
            <div
                style={{ width: "70%" }}
                className="pull-left">
                {showParcelle ? <FormGroup>
                    <b style={{ "float": "left", width: 150, marginRight: 15 }}><Message msgId={"cadastrapp.relevepropriete.data"}/>: </b>
                    <Radio checked={useParcelle} value={"true"} onChange={() => setUseParcelle(true)} inline>
                        <Message msgId={"cadastrapp.relevepropriete.partial"}/>
                    </Radio>s
                    <Radio checked={!useParcelle} value={"false"} onChange={() => setUseParcelle(false)} inline>
                        <Message msgId={"cadastrapp.relevepropriete.full"}/>
                    </Radio>
                </FormGroup> : null}
                <FormGroup>
                    <b style={{ "float": "left", width: 150, marginRight: 15 }}><Message msgId={"cadastrapp.relevepropriete.type.title"}/>:</b>
                    <Radio checked={format === 'pdf'} value="pdf" onChange={() => setFormat("pdf")} inline>
                        <Message msgId={"cadastrapp.relevepropriete.type.pdf"}/>
                    </Radio>
                    <Radio checked={format === 'csv'} value="csv" onChange={() => setFormat("csv")} inline>
                        <Message msgId={"cadastrapp.relevepropriete.type.csv"}/>
                    </Radio>
                </FormGroup>
            </div>
            <div
                style={{ width: "30%" }}
                className="pull-left">
                <Button
                    disabled={selected.length === 0 || loading}
                    onClick={() => {
                        setLoading(true);
                        const handler = format === 'csv' ? createReleveProprieteAsCSV : createRelevePropriete;
                        handler({
                            parcelleId: useParcelle ? parcelle : undefined,
                            compteCommunal: data
                                .filter((_, i) => selected.includes(i))
                                .map(({ comptecommunal }) => comptecommunal)
                                .filter(function onlyUnique(value, index, self) {
                                    return self.indexOf(value) === index;
                                })
                                .join(',')
                        }).then((response) => {
                            setLoading(false);
                            downloadResponse(response);
                        }).catch(() => {
                            setLoading(false); // TODO: handle error
                        });
                    }}
                    className="pull-right">
                    {loading ? <Spinner spinnerName="circle" noFadeIn overrideSpinnerClassName="spinner" /> : null}
                    <Message msgId={"cadastrapp.relevepropriete.export"}/>
                </Button>
            </div>
            <hr/>
        </div>);
}
Example #9
Source File: Plot.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 5 votes vote down vote up
export function PlotInformationRadio({
    isCNIL1,
    isCNIL2,
    baseMaps = [],
    parcelle,
    selectedStyle = {},
    isShown,
    modalStyle
}) {
    const [baseMap, setBaseMap] = useState();
    const [personalData, setPersonalData] = useState("0");
    const [loading, setLoading] = useState(false);
    let className = isShown ? "" : "collapse";
    const hr = !modalStyle ? <hr/> : null;
    const {
        opacity,
        fillcolor,
        strokewidth,
        strokecolor
    } = toParams(selectedStyle);
    return (
        <div {...modalStyle && {style: modalStyle}} className={className}>
            {hr}
            <div
                style={{ width: modalStyle ? "100%" : "70%" }}
                className="pull-left">
                {isCNIL1 || isCNIL2 ? <FormGroup>
                    <b className={'cadastrapp-formgroup-label'}><Message msgId={"cadastrapp.bordereauparcellaire.data.title"}/>: </b>
                    <Radio inline checked={personalData === "0"} onChange={() => setPersonalData("0")} value="0">
                        <Message msgId={"cadastrapp.bordereauparcellaire.data.without"}/>
                    </Radio>
                    <Radio inline checked={personalData === "1"} onChange={() => setPersonalData("1")} value="1">
                        <Message msgId={"cadastrapp.bordereauparcellaire.data.with"}/>
                    </Radio>
                </FormGroup> : null}
                <FormGroup>
                    <b className={'cadastrapp-formgroup-label'}><Message msgId={"cadastrapp.bordereauparcellaire.basemap"}/>:</b>
                    <div style={{ "float": "left" }}>
                        <DropdownList style={{width: 300}} value={baseMap} defaultValue={baseMaps[0]} onSelect={v => setBaseMap(v)} textField="title" data={baseMaps} itemComponent={ListItem} />
                    </div>
                </FormGroup>
            </div>
            <div

                style={{ width: modalStyle ? "100%" : "30%" }}
                className="pull-left">
                <Button
                    disabled={loading}
                    onClick={() => {
                        const idx = baseMaps.indexOf(baseMap);
                        const baseMapIndex = idx >= 0 ? idx : 0;
                        setLoading(true);
                        createBordereauParcellaire({
                            fillcolor,
                            opacity,
                            strokecolor,
                            strokewidth,
                            parcelle,
                            ...((isCNIL1 || isCNIL2) && {personaldata: personalData}),
                            basemapindex: baseMapIndex
                        }).then((response) => {
                            setLoading(false);
                            downloadResponse(response);
                        }).catch(() => {
                            setLoading(false); // TODO: handle error
                        });
                    }}
                    className="pull-right">
                    {loading ? <Spinner spinnerName="circle" noFadeIn overrideSpinnerClassName="spinner" /> : null}
                    <Message msgId={"cadastrapp.bordereauparcellaire.export"}/>
                </Button>
            </div>
            {hr}
        </div>);
}
Example #10
Source File: ContentUpgradeLayout.js    From Edlib with GNU General Public License v3.0 5 votes vote down vote up
ContentUpgradeLayout = ({
    onClick,
    libraries,
    showConfirm,
    onConfirm,
    upgradeComplete,
    onToggleConfirm,
    onUndoUpgrade,
    percentProgress,
    inProgress,
    translations,
    selectedLibraryId,
}) => {
    return (
        <div className="upgradeVersionContainer">
            {(upgradeComplete !== true && inProgress !== true) && (
                <>
                    <FormGroup controlId="formControlsSelect">
                        <FormControl
                            componentClass="select"
                            onChange={onClick}
                            value={selectedLibraryId}
                        >
                            <option value="">{translations.selectVersion}</option>
                            {libraries.map((library, index) => {
                                return (
                                    <option key={index} value={library.id}>{library.version}</option>
                                );
                            })}
                        </FormControl>
                    </FormGroup>
                    <ModalWindow
                        show={showConfirm}
                        onHide={onToggleConfirm}
                        header={
                            <div>
                                {translations.confirmation}
                            </div>
                        }
                        footer={
                            <div>
                                <Button onClick={onConfirm} bsStyle="success">
                                    {translations.yes}
                                </Button>
                                <Button onClick={onToggleConfirm} bsStyle="danger">
                                    {translations.no}
                                </Button>
                            </div>
                        }
                    >
                        {translations.upgradeConfirmation}
                    </ModalWindow>
                </>
            )}
            {(inProgress === true || upgradeComplete === true) && (
                <>
                    <ControlLabel>{translations.progress}</ControlLabel>
                    <ProgressBar
                        now={percentProgress}
                        label={`${percentProgress}%`}
                    />
                </>
            )}
            {upgradeComplete === true && (
                <div className="contentupgrade-complete">
                    <div>{translations.undoTextHTML}</div>
                    <Button
                        bsStyle="danger"
                        onClick={onUndoUpgrade}
                    >
                        {translations.undo}
                    </Button>
                </div>
            )}
        </div>
    );
}
Example #11
Source File: examples.js    From create-sas-app with Apache License 2.0 5 votes vote down vote up
editFileExample = props => {
	const file = props.state.editFile
	const content = (file && file.content) || ''
	return <div>
		<h5 className={'mb-0'}>Update file</h5>
		<code>updateFile(fileName, fileBlob, lastModified, overwrite, options)</code>
		<div>If overwrite = <span className={'text-danger'}>false</span> you will be notified if file was edited in the
			meantime
		</div>
		<div>
			<label className={'mr-2'}>file:</label><span className={'comment'}>{file && file.name + '.txt'}</span>
		</div>
		<Row className={'mt-3'}>
			<Col md={5}>
				<FormGroup>
					<FormControl
						as="textarea" rows="3"
						value={content}
						onChange={e => {
							let v = e.target.value
							const editFile = props.state.editFile
							editFile.content = v
							props.setState({editFile})
						}}
					/>
				</FormGroup>
			</Col>
			<Col md={2}>
				<button
					className={'btn btn-primary mr-2 btn-loading'}
					onClick={props.updateFile}
					disabled={!file || !file.name || !file.content}
				>
					{props.state.updatingFile && <i className={'fas fa-spinner fa-spin'}/>} Update
				</button>
			</Col>
		</Row>
		{props.state.editFileError && <div className={'text-danger'}>props.state.editFileError</div>}
	</div>
}
Example #12
Source File: examples.js    From create-sas-app with Apache License 2.0 5 votes vote down vote up
createNewFileExample = props => {
	return <div>
		<h3 className={'mb-3'}>Files methods examples</h3>
		<h5 className={'mb-0'}>Create new file</h5>
		<code>createNewFile(fileName, fileBlob, parentFolderUri, options)</code>
		<Row>
			<Col md={1}>fileName: </Col>
			<Col md={4} className={'comment'}>{props.state.newFileName ? props.state.newFileName + '.txt' : 'unknown'}</Col>
		</Row>
		<Row>
			<Col md={1}>fileBlob: </Col>
			<Col md={4} className={'comment'}>{<pre
				className={'text-inline'}>{JSON.stringify(props.fileContent, null, 2)}</pre>}</Col>
		</Row>
		<div>
			<label className={'mr-2'}>parentFolderUri:</label><span className={'comment'}>{props.state.folderDetails ?
			Utils.getSelfUri(props.state.folderDetails.links) :
			<Button
				bsstyle={'btn-sm btn-primary mr-2'}
				onClick={props.getFolderDetails}>Get
			</Button>}</span>
		</div>
		<Row className={'mt-3'}>
			<Col md={5}>
				<FormGroup>
					<FormControl
						type={'text'}
						placeholder={'fileName'}
						value={props.state.newFileName}
						onChange={e => props.setState({newFileName: e.target.value})}
					/>
				</FormGroup>
			</Col>
			<Col md={2}>
				<Button
					bsstyle={'btn btn-primary mr-2 btn-loading'}
					onClick={props.createNewFile}
					disabled={!props.state.folderDetails || !props.state.newFileName || props.state.creatingNewFile}
				>
					{props.state.creatingNewFile && <i className={'fas fa-spinner fa-spin'}/>} Create
				</Button>
			</Col>
		</Row>
	</div>
}
Example #13
Source File: DirectoryAddUpdate.jsx    From maps with MIT License 4 votes vote down vote up
export default function DirectoryAddUpdate() {
  const [coopName, setCoopName] = useState("");
  const [street, setStreet] = useState("");
  const [addressPublic, setAddressPublic] = useState(DEFAULT_FORM_YES_NO);
  const [city, setCity] = useState("");
  const [state, setState] = useState("IL");
  const [zip, setZip] = useState("");
  const [county, setCounty] = useState("");
  const [country, setCountry] = useState(DEFAULT_COUNTRY_CODE);
  const [websites, setWebsites] = useState("");
  const [contactName, setContactName] = useState("");
  const [contactNamePublic, setContactNamePublic] = useState(DEFAULT_FORM_YES_NO);
  const [contactEmail, setContactEmail] = useState("");
  const [contactEmailPublic, setContactEmailPublic] = useState(DEFAULT_FORM_YES_NO);
  const [contactPhone, setContactPhone] = useState("");
  const [contactPhonePublic, setContactPhonePublic] = useState(DEFAULT_FORM_YES_NO);
  const [entityTypes, setEntityTypes] = useState([]);
  const [scope, setScope] = useState("Local");
  const [tags, setTags] = useState("");
  const [descEng, setDescEng] = useState("");
  const [descOther, setDescOther] = useState("");
  const [reqReason, setReqReason] = useState("Add new record");

  // Holds country and state list
  const [countries, setCountries] = React.useState([]);
  const [provinces, setProvinces] = React.useState([]);
  const [entities, setEntityTypeList] = React.useState([]);

  // Validation
  const [errors, setErrors, getErrors] = React.useState();

  // Errors when loading already existing entity
  const [loadErrors, setLoadErrors] = React.useState("");

  // While loading coop data from ID
  const [loadingCoopData, setLoadingCoopData] = React.useState(false);

  // Alert provider state
  const [ open ] = useAlert();

  // Gets id from URL
  const { id } = useParams();

  const clearForm = () => {
    // Resets the initial form values to clear the form
    setCoopName("");
    setStreet("");
    setAddressPublic(DEFAULT_FORM_YES_NO);
    setCity("");
    setState("IL");
    setZip("");
    setCounty("");
    setCountry(DEFAULT_COUNTRY_CODE);
    setWebsites("");
    setContactName("");
    setContactNamePublic(DEFAULT_FORM_YES_NO);
    setContactEmail("");
    setContactEmailPublic(DEFAULT_FORM_YES_NO);
    setContactPhone("");
    setContactPhonePublic(DEFAULT_FORM_YES_NO);
    setEntityTypes([]);
    setScope("Local");
    setTags("");
    setDescEng("");
    setDescOther("");
    setErrors();
  }

  // Check required fields to see if they're still blank 
  const requiredFields = [coopName, websites, contactName, contactEmail, contactPhone, entityTypes];

  const updateRequired = (field) => {
    const asArray = Object.entries(errors);

    let filteredItem = "";

    switch(field) {
      case coopName:
        filteredItem = "coop_name";
        break;
      case websites:
        filteredItem = "websites";
        break;
      case contactName:
        filteredItem = "contact_name";
        break;
      case contactEmail:
        filteredItem = "contact";
        break;
      case contactPhone:
        filteredItem = "contact";
        break;
      case entityTypes:
        filteredItem = "entity_types";
        break;
    }

    if (errors.hasOwnProperty(filteredItem)) {
      setErrors(Object.fromEntries(asArray.filter(([key, value]) => key !== filteredItem)));
    };
  }

  const checkRequired = () => {
    if (!errors) {
      return
    } else {
      requiredFields.forEach(field => {
        if (field.length !== 0) {
          updateRequired(field);
        }
      })
    }
  }

  // Router history for bringing user to search page on submit
  const history = useHistory();

  const fetchCoopForUpdate = async () => {
    setLoadingCoopData(true);

    try {
      const res = await fetch(REACT_APP_PROXY + `/coops/${id}/`);
      if (!res.ok) {
        throw Error("Cannot access requested entity.");
      }
      const coopResults = await res.json();

      setCoopName(coopResults.name ? coopResults.name : "");
      setStreet(
        coopResults.addresses[0].formatted
          ? coopResults.addresses[0].formatted
          : ""
      );
      setCity(
        coopResults.addresses[0].locality.name
          ? coopResults.addresses[0].locality.name
          : ""
      );
      setState(
        coopResults.addresses[0].locality.state.code
          ? coopResults.addresses[0].locality.state.code
          : ""
      );
      setZip(
        coopResults.addresses[0].locality.postal_code
          ? coopResults.addresses[0].locality.postal_code
          : ""
      );
      setCountry(
        coopResults.addresses[0].locality.state.country.code
          ? coopResults.addresses[0].locality.state.country.code
          : ""
      );
      setWebsites(coopResults.web_site ? coopResults.web_site : "");
      setContactEmail(coopResults.email ? coopResults.email : "");
      setContactPhone(coopResults.phone ? coopResults.phone.phone : "");
      setEntityTypes(
        [coopResults.types[0]]
          ? [coopResults.types.map((type) => type.name)]
          : []
      );
      setReqReason("Update existing record");
    } catch (error) {
      console.error(error);
      setLoadErrors(`Error: ${error.message}`);
    } finally {
      setLoadingCoopData(false);
    }
  };

  const submitForm = (e) => {
    e.preventDefault();

    console.log("form submitted!");
    console.log(coopName);

    let formData = {
      coop_name: coopName,
      street: street,
      address_public: addressPublic,
      city: city,
      state: state,
      zip: zip,
      county: county,
      country: country,
      websites: websites,
      contact_name: contactName,
      contact_name_public: contactNamePublic,
      contact_email: contactEmail,
      contact_email_public: contactEmailPublic,
      contact_phone: contactPhone,
      contact_phone_public: contactPhonePublic,
      entity_types: entityTypes.join(", "),
      scope: scope,
      tags: tags,
      desc_english: descEng,
      desc_other: descOther,
      req_reason: reqReason,
      id: id,
    };

    CoopService.saveToGoogleSheet(
      formData,
      (errors) => {
        //setButtonDisabled(false);
        setErrors(errors);
      },
      function (data) {
        const result = data;
        clearForm();
        window.scrollTo(0, 0);

        // Alert message
        const message = `Form Submission for ${coopName} successful`
        if (message) open(message);

        // If update request, redirects user to search page on form submit.
        if (id) {
          history.push('/search');
        }
      }
    );
  };

  useEffect(() => {
    // Get initial countries
    fetch(REACT_APP_PROXY + "/countries/")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const initialCountries = data.map((country) => {
          return country;
        });
        setCountries(initialCountries);
      });

    // Get initial provinces (states)
    fetch(REACT_APP_PROXY + "/states/" + DEFAULT_COUNTRY_CODE)
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const initialProvinces = data.map((province) => {
          return province;
        });
        setProvinces(initialProvinces);
      });

    //   Get initial entity types
    fetch(REACT_APP_PROXY + "/predefined_types/")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const initialEntityTypes = data.map((entity) => {
          return entity;
        });
        setEntityTypeList(initialEntityTypes);
      });

    if (id) {
      fetchCoopForUpdate();
    }
  }, []);

  // Checking required field changes with useEffect.
  useEffect(() => {
      checkRequired();
    },
    requiredFields);

  return (
    <div className="directory-form">
      <h1 className="form__title">Directory Form</h1>
      <h2 className="form__desc">
        Use this form to add or request the update of a solidarity entity or
        cooperative. We'll contact you to confirm the information
      </h2>
      <h2 className="form__desc">
        <span style={{ color: "red" }}>*</span> = required
      </h2>
      {loadErrors && (
        <strong className="form__error-message">
          {JSON.stringify(loadErrors)}
        </strong>
      )}
      {loadingCoopData && <strong>Loading entity data...</strong>}
      <div className="form">
        <form
          onSubmit={submitForm}
          className="container-fluid"
          id="directory-add-update"
          noValidate
        >
          <FormGroup>
            <div className="form-row">
              <div className="form-group col-md-6 col-lg-4 col-xl-3">
                <Input
                  className={"required"}
                  type={"text"}
                  title={"Cooperative/Entity Name"}
                  name={"coop_name"}
                  value={coopName}
                  placeholder={"Cooperative/entity name"}
                  handleChange={(e) => setCoopName(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              <div className="form-group col-md-6 col-lg-3 col-xl-3">
                <Input
                  type={"text"}
                  title={"Street Address"}
                  name={"street"}
                  value={street}
                  placeholder={"Address street"}
                  handleChange={(e) => setStreet(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              <div className="form-group col-md-4 col-lg-3 col-xl-2">
                <Input
                  type={"text"}
                  title={"City"}
                  name={"city"}
                  value={city}
                  placeholder={"Address city"}
                  handleChange={(e) => setCity(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              <div className="form-group col-md-3 col-lg-2 col-xl-2">
                <Province
                  title={"State"}
                  name={"state"}
                  options={provinces}
                  value={state}
                  placeholder={"Select State"}
                  handleChange={(e) => setState(e.target.value)}
                />{" "}
              </div>
              <div className="form-group col-md-2 col-lg-2 col-xl-2">
                <Input
                  type={"text"}
                  title={"Zip Code"}
                  name={"zip"}
                  value={zip}
                  placeholder={"Zip code"}
                  handleChange={(e) => setZip(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              <div className="form-group col-md-3 col-lg-2 col-xl-3">
                <Input
                  type={"text"}
                  title={"County"}
                  name={"county"}
                  value={county}
                  placeholder={"County"}
                  handleChange={(e) => setCounty(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              <div className="form-group col-md-4 col-lg-2 col-xl-3">
                <Country
                  title={"Country"}
                  name={"country"}
                  options={countries}
                  value={country}
                  countryCode={"US"}
                  placeholder={"Select Country"}
                  handleChange={(e) => setCountry(e.target.value)}
                />{" "}
              </div>
              <div className="form-group col-md-8 col-lg-6 col-xl-5">
                <DropDownInput
                  type={"select"}
                  as={"select"}
                  title={"Is Address to be public on the map?"}
                  name={"address_public"}
                  value={addressPublic}
                  multiple={""}
                  handleChange={(e) => setAddressPublic(e.target.value)}
                  options={[
                    { id: "yes", name: "Yes" },
                    { id: "no", name: "No" },
                  ]}
                />
              </div>
              <div className="form-group col-md-12">
                <Input
                  className={"required"}
                  type={"text"}
                  title={
                    "Website or Social Media Page (separate multiple links with a comma)"
                  }
                  name={"websites"}
                  value={websites}
                  placeholder={"Website or social media pages"}
                  handleChange={(e) => setWebsites(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              <div className="form-group col-md-6">
                <Input
                  className={"required"}
                  type={"text"}
                  title={"Cooperative/Entity Contact Person Name"}
                  name={"contact_name"}
                  value={contactName}
                  placeholder={"Contact name"}
                  handleChange={(e) => setContactName(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              <div className="form-group col-md-6">
                <DropDownInput
                  className={"required"}
                  type={"select"}
                  as={"select"}
                  title={"Is Contact name to be public on the map?"}
                  name={"contact_name_public"}
                  value={contactNamePublic}
                  multiple={""}
                  handleChange={(e) => setContactNamePublic(e.target.value)}
                  options={[
                    { id: "yes", name: "Yes" },
                    { id: "no", name: "No" },
                  ]}
                />
              </div>
              <div className="form-group col-12 form__desc required">
                You must include at least either a phone number or an e-mail address.
              </div>
              <div className="form-group col-md-4 col-lg-4">
                <Input
                  type={"email"}
                  title={"Contact Email Address"}
                  name={"contact_email"}
                  value={contactEmail}
                  placeholder={"Contact email"}
                  handleChange={(e) => setContactEmail(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              {contactEmail ? (
                <div className="form-group col-md-6 col-lg-6">
                  <DropDownInput
                    className={"required"}
                    type={"select"}
                    as={"select"}
                    title={"Is Email to be public on the map?"}
                    name={"contact_email_public"}
                    multiple={""}
                    value={contactEmailPublic}
                    handleChange={(e) => setContactEmailPublic(e.target.value)}
                    options={[
                      { id: "yes", name: "Yes" },
                      { id: "no", name: "No" },
                    ]}
                  />
                </div>
              ) : (
                <div className="form-group col-md-6 col-lg-6"></div>
              )}
              <div className="form-group col-md-4 col-lg-4">
                <Input
                  type={"tel"}
                  title={"Contact Phone Number"}
                  name={"contact_phone"}
                  value={contactPhone}
                  placeholder={"Contact phone"}
                  handleChange={(e) => setContactPhone(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              {contactPhone ? (
                <div className="form-group col-md-8 col-lg-6">
                  <DropDownInput
                    className={"required"}
                    type={"select"}
                    as={"select"}
                    title={"Is Phone number to be public on the map?"}
                    name={"contact_phone_public"}
                    value={contactPhonePublic}
                    multiple={""}
                    handleChange={(e) => setContactPhonePublic(e.target.value)}
                    options={[
                      { id: "yes", name: "Yes" },
                      { id: "no", name: "No" },
                    ]}
                  />
                </div>
              ) : (
                <div className="form-group col-md-8 col-lg-6"></div>
              )}
              <div className="col-12">
                <Input
                  type={"hidden"}
                  title={""}
                  name={"contact"}
                  value={''}
                  placeholder={"Contact info"}
                  errors={errors}
                  required={0}
                />{" "}
              </div>
              <div className="form-group col-md-6 col-lg-6">
                <DropDownInput
                  className={"required"}
                  type={"select"}
                  as={"select"}
                  title={"Entity types"}
                  multiple={"multiple"}
                  name={"entity_types"}
                  value={entityTypes}
                  handleChange={(e) =>
                    setEntityTypes(
                      [].slice
                        .call(e.target.selectedOptions)
                        .map((item) => item.value)
                    )
                  }
                  options={entities}
                  errors={errors}
                />
              </div>
              <div className="form-group col-md-6 col-lg-4">
                <DropDownInput
                  type={"select"}
                  as={"select"}
                  title={"Scope of Service"}
                  name={"scope"}
                  value={scope}
                  multiple={""}
                  handleChange={(e) => setScope(e.target.value)}
                  options={[
                    { id: "local", name: "Local" },
                    { id: "regional", name: "Regional" },
                    { id: "national", name: "National" },
                    { id: "international", name: "International" },
                  ]}
                />
              </div>
              <div className="form-group col-md-12 col-lg-12 col-xl-10">
                <Input
                  type={"text"}
                  title={"Add description tags here, separated by commas"}
                  name={"tags"}
                  value={tags}
                  placeholder={"Enter tags"}
                  handleChange={(e) => setTags(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              <div className="form-group col-md-12 col-lg-6 col-xl-4">
                <TextAreaInput
                  type={"textarea"}
                  as={"textarea"}
                  title={"Entity Description (English)"}
                  name={"desc_english"}
                  value={descEng}
                  placeholder={"Enter entity description (English)"}
                  handleChange={(e) => setDescEng(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              <div className="form-group col-md-12 col-lg-6 col-xl-4">
                <TextAreaInput
                  type={"textarea"}
                  as={"textarea"}
                  title={"Entity Description (Other Language)"}
                  name={"desc_other"}
                  value={descOther}
                  placeholder={"Enter entity description (Other Language)"}
                  handleChange={(e) => setDescOther(e.target.value)}
                  errors={errors}
                />{" "}
              </div>
              <div className="form-group col-md-8 col-lg-8 col-xl-4">
                <DropDownInput
                  className={"required"}
                  type={"select"}
                  as={"select"}
                  title={"Please list your reason for submitting this request"}
                  name={"req_reason"}
                  value={reqReason}
                  multiple={""}
                  handleChange={(e) => setReqReason(e.target.value)}
                  options={[
                    { id: "add", name: "Add new record" },
                    { id: "update", name: "Update existing record" },
                  ]}
                />
              </div>
              <div className="form-group col-md-6" align="center">
                <Button buttonType={"primary"} title={"Send Addition/Update"} type={"submit"} />
              </div>
              <div className="form-group col-md-6" align="center">
                <CancelButton id={id} />
              </div>
            </div>
            {errors && (
              <strong className="form__error-message">
                Please correct the errors above and then resubmit.
              </strong>
            )}
          </FormGroup>
        </form>
      </div>
    </div>
  );
}
Example #14
Source File: Search.jsx    From maps with MIT License 4 votes vote down vote up
Search = (props) => {
  //store evolving search settings before search form is submitted
  const [coopSearchSettings, setCoopSearchSettings] = useState({ state: "IL", type: [] });

  // store finalized search url
  const [searchUrl, setSearchUrl] = useState("");

  const [coopTypes, setCoopTypes] = React.useState([]);
  const [provinces, setProvinces] = React.useState([]);
  const [searchResults, setSearchResults] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // Get all possible coop types to populate search form
    fetch(REACT_APP_PROXY + "/coop_types/")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const coopTypes = data.map((coopType) => {
          return coopType;
        });
        setCoopTypes(coopTypes.sort((a, b) => (a.name > b.name ? 1 : -1)));
      });
  }, []);

  useEffect(() => {
    // Get initial provinces (states)
    fetch(REACT_APP_PROXY + "/states/" + DEFAULT_COUNTRY_CODE)
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const initialProvinces = data.map((province) => {
          return province;
        });
        setProvinces(initialProvinces);
      });
  }, []);

  useEffect(
    () => {
      // set searchResults to empty if searchUrl is empty
      if (searchUrl === "") {
        setSearchResults([]);
        return;
      } else {
        //Let the debounced function do it's thing
        const results = doSearchDebounced(
          coopSearchSettings,
          setSearchResults,
          setLoading,
          searchUrl
        );
        setSearchResults(results);
      }
    },
    // Only re-render page if searchUrl has changed.
    // coopSearchSettings is not a dependency because we do want not re-render page
    // every time users type a new character in search form.
    [searchUrl]
  );

  const handleInputChange = (event) => {
    // save user edits to individual form fields to coopSearchSettings
    const { target } = event;
    const { name, value } = target;
    event.persist();
    setCoopSearchSettings({ ...coopSearchSettings, [name]: value });
  };

  const handleFormSubmit = (e) => {
    // when the user finalizes search settings by pressing 'submit,'
    // built out search URL
    e.preventDefault();
    buildSearchUrl(coopSearchSettings, setSearchUrl);
  };

  const formatAddress = (obj) => {
    const streetAdd = obj.formatted;
    const cityName = obj.locality.name;
    const stateCode = obj.locality.state.code;
    const zip = obj.locality.postal_code;

    return streetAdd + ", " + cityName + ", " + stateCode + " " + zip;
  };

  const handleMultiSelect = (e) => {
    const { name, value } = e.target;
    const selected = coopSearchSettings[name]
    const index = selected.indexOf(value)

    if (index > -1) {
      selected.splice(index, 1)
    } else {
      selected.push(value)
    }
    setCoopSearchSettings({...coopSearchSettings, [name]: selected})
  }

  // same logic from Search.jsx
  const renderSearchResults = () => {
    if (searchResults && searchResults.length) {
      return (
        <>
          <br/>
          <ListGroup variant="flush">
            <ListGroupItem key="header">
              <h3 className="float-left font-weight-bold">
                Matching Entities
              </h3>
              <h3 className="float-right font-weight-bold">
                Edit
              </h3>
            </ListGroupItem>
            {searchResults.map((item) => (
              <ListGroupItem key={item.id} value={item.name}>
                <div className="float-left">
                  {item.name}
                  <br />
                  {formatAddress(item.addresses[0])}
                </div>
                <span className="float-right">
                  <Link to={"/directory-additions-updates/" + item.id}>
                    <PencilSquare color="royalblue" size={26} />
                  </Link>
                </span>
              </ListGroupItem>
            ))}
          </ListGroup>
        </>
      );
    }
  };

  return (
    <div className="form container-fluid">
      <form
          onSubmit={handleFormSubmit}
        >
        {/* FormGroup logic from FormContainer.jsx */}
        <FormGroup controlId="formBasicText">
          {/* FormLabel and FormControl logic from Input.jsx */}
          <div className="form-row">
            <div className="form-group col-md-6 col-lg-6 col-xl-6">
              <FormLabel class="formInputStyle">Name</FormLabel>
              <FormControl
                class="form-control"
                id={"name"}
                name={"name"}
                value={coopSearchSettings.name}
                placeholder="Enter cooperative name"
                onChange={handleInputChange}
                aria-label="Name"
              />{" "}
            </div>
            <div className="form-group col-md-6 col-lg-6 col-xl-6">
              <DropDownInput
                className={"formInputStyle"}
                type={"select"}
                as={"select"}
                title={"CoOp Type"}
                multiple={"multiple"}
                name={"type"}
                value={coopSearchSettings.type}
                handleChange={handleMultiSelect}
                options={coopTypes}
              />
            </div>
          </div>
          <div className="form-row">
            <div className="form-group col-md-6 col-lg-6 col-xl-6">
              <FormLabel class="formInputStyle">Street</FormLabel>
              <FormControl
                class="form-control"
                id={"street"}
                name={"street"}
                value={coopSearchSettings.street}
                placeholder="Enter address street"
                onChange={handleInputChange}
              />{" "}
            </div>
            <div className="form-group col-md-3 col-lg-3 col-xl-3">
              <FormLabel class="formInputStyle">City</FormLabel>
              <FormControl
                class="form-control"
                id={"city"}
                name={"city"}
                value={coopSearchSettings.city}
                placeholder="Enter address city"
                onChange={handleInputChange}
              />{" "}
              </div>
            <div className="form-group col-md-3 col-lg-3 col-xl-3">
              <FormLabel class="formInputStyle">Postal Code</FormLabel>
              <FormControl
                class="form-control"
                id={"zip"}
                name={"zip"}
                value={coopSearchSettings.zip}
                placeholder="Enter postal code"
                onChange={handleInputChange}
              />{" "}
            </div>
          </div>
          <div className="form-row">
            <div className="form-group col-md-3 col-lg-6 col-xl-6">
              <FormLabel class="formInputStyle">County</FormLabel>
              <FormControl
                class="form-control"
                id={"county"}
                name={"county"}
                value={coopSearchSettings.county}
                placeholder="Enter county"
                onChange={handleInputChange}
              />{" "}
            </div>
            <div className="form-group col-md-3 col-lg-3 col-xl-3">
              <Province
                title={"State"}
                className="formInputStyle"
                name={"state"}
                options={provinces}
                value={coopSearchSettings.state}
                placseholder={"Select state"}
                handleChange={(e) =>
                  setCoopSearchSettings({
                    ...coopSearchSettings,
                    [e.target.name]: e.target.value,
                  })
                }
              />{" "}
            </div>
            <div className="form-group col-md-3 col-lg-3 col-xl-3">
              <label class="form-label" class="formInputStyle">
                Enabled
              </label>
              <select
                name={"enabled"}
                value={coopSearchSettings.enabled}
                onChange={handleInputChange}
                className="form-control"
              >
                <option selected value="none">
                  None Selected
                </option>
                <option value="true">True</option>
                <option value="False">False</option>
              </select>
            </div>
          </div>
          <div className="form-group form-row">
            <div className="form-group col-md-6" align="center">
              <Button buttonType={"primary"} title={"Submit"} type={"submit"} />{" "}
            </div>
            <div className="form-group col-md-6" align="center">
              <CancelButton />
            </div>
          </div>
          <div>
            {renderSearchResults()}
            {loading && (
              <div class="loading">
                <div className="spinner-border" role="status">
                  <span className="sr-only">Loading...</span>
                </div>
              </div>
            )}
          </div>
        </FormGroup>
      </form>
    </div>
  );
}
Example #15
Source File: FormContainer.jsx    From maps with MIT License 4 votes vote down vote up
FormContainer = (props) => {
  const [countries, setCountries] = React.useState([]);
  const [provinces, setProvinces] = React.useState([]);
  const [errors, setErrors] = React.useState([]);
  const [coopTypes, setCoopTypes] = React.useState([]);
  const [coop, setCoop] = React.useState(props.coop);
  const history = useHistory();
  const [open, close] = useAlert();
  const [buttonDisabled, setButtonDisabled] = useState(false);
  console.log("coop:");
  console.log(coop);

  const handleFormSubmit = (e) => {
    e.preventDefault();
    setButtonDisabled(true);
    CoopService.save(
      coop,
      (errors) => {
        setButtonDisabled(false);
        setErrors(errors);
      },
      function (data) {
        const result = data;
        history.push({
          pathname: "/" + result.id + "/people",
          state: { coop: result, message: "Success" },
        });
        window.scrollTo(0, 0);
      }
    );
  };

  const handleClearForm = () => {
    // Logic for resetting the form
  };

  const handleCoopTypeAddition = (tag) => {
    const coopCopy = JSON.parse(JSON.stringify(coop));
    const types = coopCopy.types;
    types[types.length] = { name: tag.text };
    setCoop(coopCopy);
  };

  const handleCoopTypeDeletion = (i) => {
    const coopCopy = JSON.parse(JSON.stringify(coop));
    let types = coopCopy.types;
    types = types.filter((type, index) => index !== i);
    coopCopy.types = types;
    setCoop(coopCopy);
  };

  const handleInput = (e) => {
    let value = e.target.value;
    let name = e.target.name;
    if (name.indexOf("[") === -1) {
      setValue(name, value);
    } else {
      const coopCopy = JSON.parse(JSON.stringify(coop));
      const keys = name.split(/[\[\].]+/);
      console.log("setting " + name + " to " + value);
      _.set(coopCopy, name, value);
      setCoop(coopCopy);
    }
  };

  const handleProvinceChange = (e) => {
    const coopCopy = JSON.parse(JSON.stringify(coop));
    const name = e.target.name.replace(".name", ".code");
    const value = e.target.value;
    console.log("setting " + name + " to " + value);
    _.set(coopCopy, name, value);
    const stateElt = document.getElementById(e.target.name);
    const stateText = stateElt.options[stateElt.selectedIndex].text;
    const coopStateName = e.target.name;
    _.set(coopCopy, coopStateName, stateText);

    // Update the parent country
    const countryName = e.target.name.replace(".name", ".country.code");
    console.log("country name:" + countryName);
    const countryElt = document.getElementById(countryName);
    const countryNameText = countryElt.options[countryElt.selectedIndex].text;
    const coopCountryAttrName = e.target.name.replace(".name", ".country.name");
    _.set(coopCopy, coopCountryAttrName, countryNameText);
    setCoop(coopCopy);
  };

  const updateValue = (name, value, index = 0) => {
    const coopCopy = JSON.parse(JSON.stringify(coop));
    if (name.length - 1 > index) {
      const isArray = Array.isArray(coop[name[index]]);
      if (isArray) {
        console.log("name:" + name);
        console.log("name index: " + name[index]);
      } else {
        console.log("other branch");
        console.log("name:" + name);
        console.log("name index: " + name[index]);
      }
    } else {
      console.log("name:" + name + " index:" + index);
      _.set(coopCopy, [name[index]], value);
      console.log("set coop copy to ...");
      console.log(coopCopy);
      //setCoop( coopCopy );
      //obj = { ...obj, [name[index]]: value };
    }
    return coopCopy;
  };

  const [checked, setChecked] = useState(true);

  const handleClick = (e) => {
    props.coop.enabled = !props.coop.enabled;

    setChecked(!checked);
  };

  /**
   * Verify phone field conforms to US phone (10 digits)
   *
   * @param  e
   */
  const handlePhoneInput = (e) => {
    let value = e.target.value.replace(/\D/, "");
    value = value.length > 10 ? value.substring(0, 10) : value;
    let name = e.target.name;
    //update phone
    setValue(name, value);
  };

  const setValue = (is, value) => {
    const coopCopy = JSON.parse(JSON.stringify(coop));
    if (typeof is == "string") {
      console.log("setting string value");
      _.set(coopCopy, is, value);
      return setCoop(coopCopy);
    } else if (is.length === 1 && value !== undefined) {
      _.set(coopCopy, is, value);
      console.log(coopCopy);
      return setCoop(coopCopy);
    } else if (is.length === 0) return coop;
    else {
      console.log("is:" + is + " value:" + value);
      return setValue(is.slice(1), value);
    }
  };

  useEffect(() => {
    // Get initial countries
    fetch(REACT_APP_PROXY + "/countries/")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const initialCountries = data.map((country) => {
          return country;
        });
        setCountries(initialCountries);
      });

    // Get initial provinces (states)
    fetch(REACT_APP_PROXY + "/states/" + DEFAULT_COUNTRY_CODE)
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const initialProvinces = data.map((province) => {
          return province;
        });
        setProvinces(initialProvinces);
      });

    // Get all possible coop types
    fetch(REACT_APP_PROXY + "/coop_types/")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const coopTypes = data.map((coopType) => {
          return coopType;
        });
        setCoopTypes(coopTypes);
      });
  }, []);

  useEffect(() => {
    const coop = props.coop;
    setCoop(coop);
  }, [props]);

  /* This life cycle hook gets executed when the component mounts */

  if (coopTypes && !coopTypes.length) {
    return null;
  }
  console.log(props.coop.enabled);
  return (
    <div className="form">
      <form className="container-fluid" onSubmit={handleFormSubmit}>
        <FormGroup controlId="formBasicText">
          <Input
            className={"required"}
            inputType={"text"}
            title={"Name"}
            name={"name"}
            value={coop.name}
            placeholder={"Enter cooperative name"}
            handleChange={handleInput}
            errors={errors}
            style={inputStyle}
          />{" "}
          {/* Name of the cooperative */}
          <CoopTypes
            className={"required"}
            name={"types"}
            suggestions={coopTypes}
            values={coop.types}
            placeholder={"Enter coop type(s)"}
            handleAddition={handleCoopTypeAddition}
            handleDeletion={handleCoopTypeDeletion}
            errors={errors}
            style={inputStyle}
          />{" "}
          {/* Coop Type Selection */}
          <Input
            className={"required"}
            inputType={"text"}
            title={"Street"}
            name={"addresses[0].formatted"}
            value={coop.addresses[0].formatted}
            placeholder={"Enter address street"}
            handleChange={handleInput}
            errors={errors}
            style={inputStyle}
          />{" "}
          {/* Address street of the cooperative */}
          <Input
            className={"required"}
            inputType={"text"}
            title={"City"}
            name={"addresses[0].locality.name"}
            value={coop.addresses[0].locality.name}
            placeholder={"Enter address city"}
            handleChange={handleInput}
            errors={errors}
            style={inputStyle}
          />{" "}
          {/* Address city of the cooperative */}
          <Country
            className={"required"}
            title={"Country"}
            name={"addresses[0].locality.state.country.code"}
            options={countries}
            countryCode={coop.addresses[0].locality.state.country.code}
            placeholder={"Select Country"}
            handleChange={handleInput}
            style={inputStyle}
          />{" "}
          {/* Country Selection */}
          <Province
            className={"required"}
            title={"State"}
            name={"addresses[0].locality.state.name"}
            options={provinces}
            value={coop.addresses[0].locality.state.code}
            placeholder={"Select State"}
            handleChange={handleProvinceChange}
            style={inputStyle}
          />{" "}
          {/* State Selection */}
          <Input
            className={"required"}
            inputType={"text"}
            title={"Postal Code"}
            name={"addresses[0].locality.postal_code"}
            value={coop.addresses[0].locality.postal_code}
            placeholder={"Enter postal code"}
            handleChange={handleInput}
            errors={errors}
            style={inputStyle}
          />{" "}
          {/* Address postal code of the cooperative */}
          {coop.addresses[0]?.latitude && coop.addresses[0]?.longitude && (
            <div>
              Lat: {coop.addresses[0]?.latitude.toFixed(3)} Lon:{" "}
              {coop.addresses[0]?.longitude.toFixed(3)}
            </div>
          )}
          <Input
            className={"required"}
            inputType={"text"}
            title={"Email"}
            name={"email.email"}
            value={coop.email?.email}
            placeholder={"Enter email"}
            handleChange={handleInput}
            errors={errors}
            style={inputStyle}
          />{" "}
          {/* Email of the cooperative */}
          <Input
            className={"required"}
            inputType={"text"}
            title={"Phone"}
            name={"phone.phone"}
            value={coop.phone?.phone}
            placeholder={"Enter phone number"}
            handleChange={handlePhoneInput}
            errors={errors}
            style={inputStyle}
          />{" "}
          {/* Phone number of the cooperative */}
          <Input
            inputType={"text"}
            title={"Web Site"}
            name={"web_site"}
            value={coop.web_site}
            placeholder={"Enter web site"}
            handleChange={handleInput}
            errors={errors}
            style={inputStyle}
          />{" "}
          {/* Web site of the cooperative */}
          <div style={{ width: "100%" }}>
            <input
              type="checkbox"
              id="enabled"
              style={{ margin: ".5rem" }}
              onClick={(e) => {
                handleClick(e);
              }}
              checked={checked}
            />
            <label for="enabled">Show on Map</label>
          </div>
          <Button
            action={handleFormSubmit}
            buttonType={"primary"}
            title={"Submit"}
            style={buttonStyle}
          />{" "}
          {/*Submit */}
          <Button
            disabled={buttonDisabled}
            action={handleClearForm}
            buttonType={"secondary"}
            title={"Clear"}
            style={buttonStyle}
          />{" "}
          {/* Clear the form */}
        </FormGroup>
      </form>
    </div>
  );
}
Example #16
Source File: PersonFormContainer.jsx    From maps with MIT License 4 votes vote down vote up
PersonFormContainer = (props) => {
  const [buttonDisabled, setButtonDisabled] = useState(false);
  const [person, setPerson] = React.useState(props.person);
  const [errors, setErrors] = React.useState([]);
  const [coop, setCoop] = React.useState(props.coop);
  const history = useHistory();

  useEffect(() => {
    setPerson(props.person);
  }, [props]);

  const handleInput = (e) => {
    let value = e.target.value;
    let name = e.target.name;
    if (name.indexOf("[") === -1) {
      setValue(name, value);
    } else {
      const personCopy = JSON.parse(JSON.stringify(person));
      const keys = name.split(/[\[\].]+/);
      _.set(personCopy, name, value);
      console.log("changed person to ...");
      console.log(personCopy);
      setPerson(personCopy);
    }
  };

  const updateValue = (obj, name, value, index = 0) => {
    if (name.length - 1 > index) {
      const isArray = Array.isArray(obj[name[index]]);
      obj[name[index]] = this.updateValue(
        isArray ? [...obj[name[index]]] : { ...obj[name[index]] },
        name,
        value,
        index + 1
      );
    } else {
      obj = { ...obj, [name[index]]: value };
    }
    return obj;
  };

  /**
   * Verify phone field conforms to US phone (10 digits)
   *
   * @param  e
   */
  const handlePhoneInput = (e) => {
    let value = e.target.value.replace(/\D/, "");
    value = value.length > 10 ? value.substring(0, 10) : value;
    let name = e.target.name;
    //update phone
    setValue(name, value);
  };

  const setValue = (is, value) => {
    const personCopy = JSON.parse(JSON.stringify(person));
    if (typeof is == "string") {
      console.log("setting string value");
      _.set(personCopy, is, value);
      return setPerson(personCopy);
    } else if (is.length === 1 && value !== undefined) {
      _.set(personCopy, is, value);
      return setPerson(personCopy);
    } else if (is.length === 0) return person;
    else {
      console.log("is:" + is + " value:" + value);
      return setValue(is.slice(1), value);
    }
  };

  const handleFormSubmit = (e) => {
    e.preventDefault();
    setButtonDisabled(true);
    // Make a copy of the object in order to remove unneeded properties

    const url = person.id
      ? REACT_APP_PROXY + "/people/" + person.id + "/"
      : REACT_APP_PROXY + "/people/";
    const method = person.id ? "PUT" : "POST";
    fetch(url, {
      method: method,
      body: JSON.stringify({
        id: person?.id,
        first_name: person.first_name,
        last_name: person.last_name,
        coops: person.coops.map((coop) => coop.id),
        contact_methods: [
          {
            type: "PHONE",
            phone: person.phone,
          },
          {
            type: "EMAIL",
            email: person.email,
          },
        ],
      }),
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        if (response.ok) {
          return response.json();
        } else {
          throw response;
        }
      })
      .then((data) => {
        const result = data;
        setButtonDisabled(false);
        history.push({
          pathname: "/edit/" + person.coops[0].id + "/people",
          state: {
            coop: result,
            message: person.id
              ? "Updated successfully."
              : "Created successfully.",
          },
        });
        window.scrollTo(0, 0);
      })
      .catch((err) => {
        setButtonDisabled(false);
        err.text().then((errorMessage) => {
          setErrors(JSON.parse(errorMessage));
        });
      });
  };

  /* This life cycle hook gets executed when the component mounts */

  return (
    <div className="form">
      <h5>{person.coops[0]?.name}</h5>
      <form className="container-fluid" onSubmit={handleFormSubmit}>
        <FormGroup controlId="formBasicText">
          <Input
            inputType={"text"}
            title={"First Name"}
            name={"first_name"}
            value={person.first_name}
            placeholder={"Enter first name"}
            handleChange={handleInput}
            errors={errors}
          />{" "}
          {/* First name of the person */}
          <Input
            inputType={"text"}
            title={"Last Name"}
            name={"last_name"}
            value={person.last_name}
            placeholder={"Enter last name"}
            handleChange={handleInput}
            errors={errors}
          />{" "}
          {/* Last name of the person */}
          <Input
            inputType={"text"}
            title={"Email"}
            name={"email"}
            value={person.email}
            placeholder={"Enter email"}
            handleChange={handleInput}
            errors={errors}
          />{" "}
          {/* Email of the person */}
          <Input
            inputType={"text"}
            title={"Phone"}
            name={"phone"}
            value={person.phone}
            placeholder={"Enter primary phone number"}
            handleChange={handlePhoneInput}
            errors={errors}
          />{" "}
          {/* Phone number of the person */}
          <Button
            disabled={buttonDisabled}
            action={handleFormSubmit}
            buttonType={"primary"}
            title={"Submit"}
            style={buttonStyle}
          />{" "}
          {/*Submit */}
          <Button
            action={handleClearForm}
            buttonType={"secondary"}
            title={"Clear"}
            style={buttonStyle}
          />{" "}
          {/* Clear the form */}
        </FormGroup>
      </form>
    </div>
  );
}
Example #17
Source File: LicenseChooser.js    From Edlib with GNU General Public License v3.0 4 votes vote down vote up
render() {
        let publicDomain = null;
        let createCommons = null;
        let attributionFields = null;
        // let disableCC0 = (this.allowedLicenses.indexOf('CC0') === -1);
        // let disableCopyright = (this.allowedLicenses.indexOf('COPYRIGHT') === -1);

        if (['PUBLICDOMAIN'].indexOf(this.state.licenseType) !== -1) {
            publicDomain = (
                <div>
                    <FormGroup controlId="publicdomain">
                        <ControlLabel className="licensechooser-group-title">
                            <FormattedMessage id="LICENSECHOOSER.PUBLICDOMAIN"/>
                        </ControlLabel>
                        <HelpIcon messageId="LICENSECHOOSER.PUBLICDOMAIN.HELP"/>
                        <RadioGroup
                            name="publicdomainlicense"
                            selectedValue={this.state.publicDomainLicense}
                            onChange={this.handlePublicDomainLicenseChange}
                        >
                            <label className="radio-inline">
                                <Radio className="radio-inline" value="CC0"/>
                                <FormattedMessage id="LICENSECHOOSER.PUBLICDOMAIN.CC0"/>
                            </label>
                            <label className="radio-inline">
                                <Radio className="radio-inline" value="PDM"/>
                                <FormattedMessage id="LICENSECHOOSER.PUBLICDOMAIN.PDM"/>
                            </label>
                        </RadioGroup>
                    </FormGroup>
                </div>
            );
        }

        if (this.state.licenseType === 'CC') {
            createCommons = (
                <div>
                    <FormGroup controlId="sharing">
                        <ControlLabel className="licensechooser-group-title">
                            <FormattedMessage id="LICENSECHOOSER.ADAPTIONS"/>
                        </ControlLabel>
                        <HelpIcon messageId="LICENSECHOOSER.ADAPTIONS-HELP"/>
                        <RadioGroup
                            name="sharing"
                            selectedValue={this.state.sharing}
                            onChange={this.handleSharingChange}
                        >
                            <label className="radio-inline">
                                <Radio className="radio-inline" value="-"/>
                                <FormattedMessage id="LICENSECHOOSER.YES"/>
                            </label>
                            <label className="radio-inline">
                                <Radio className="radio-inline" value="ND"/>
                                <FormattedMessage id="LICENSECHOOSER.NO"/>
                            </label>
                            <label className="radio-inline">
                                <Radio className="radio-inline" value="SA"/>
                                <FormattedMessage id="LICENSECHOOSER.OPTION-SHAREALIKE"/>
                            </label>
                        </RadioGroup>
                    </FormGroup>

                    <FormGroup controlId="commercial">
                        <ControlLabel className="licensechooser-group-title">
                            <FormattedMessage id="LICENSECHOOSER.COMMERCIAL-USE"/>
                        </ControlLabel>
                        <HelpIcon messageId="LICENSECHOOSER.COMMERCIAL-USE-HELP"/>
                        <RadioGroup
                            name="commercial"
                            selectedValue={this.state.commercial}
                            onChange={this.handleCommercialChange}
                        >
                            <label className="radio-inline">
                                <Radio value="-" className="radio-inline"/>
                                <FormattedMessage id="LICENSECHOOSER.YES"/>
                            </label>
                            <label className="radio-inline">
                                <Radio value="NC" className="radio-inline"/>
                                <FormattedMessage id="LICENSECHOOSER.NO"/>
                            </label>
                        </RadioGroup>
                    </FormGroup>
                </div>
            );
        }

        if (this.props.useAttribution && this.state.licenseType !== 'EDLL') {
            attributionFields = (
                <div className="licensechooser-attribution-container">
                    <ControlLabel className="licensechooser-group-title">
                        <FormattedMessage id="LICENSECHOOSER.ATTRIBUTION-TITLE"/>
                    </ControlLabel>
                    <HelpIcon messageId="LICENSECHOOSER.ATTRIBUTION-HELP"/>

                    <FormGroup>
                        <ControlLabel className="licensechooser-input-title">
                            <FormattedMessage id="LICENSECHOOSER.ATTRIBUTION-FIELD-TITLE"/>
                        </ControlLabel>
                        <FormControl
                            type="text"
                            value={this.props.attributionTitle}
                            placeholder={this.props.intl.formatMessage({ id: 'LICENSECHOOSER.ATTRIBUTION-FIELD-TITLE-PLACEHOLDER' })}
                            onChange={this.handleAttributionTitle}
                        />
                    </FormGroup>

                    <FormGroup>
                        <ControlLabel className="licensechooser-input-title">
                            <FormattedMessage id="LICENSECHOOSER.ATTRIBUTION-FIELD-NAME"/>
                        </ControlLabel>
                        <FormControl
                            type="text"
                            value={this.props.attributionName}
                            placeholder={this.props.intl.formatMessage({ id: 'LICENSECHOOSER.ATTRIBUTION-FIELD-NAME-PLACEHOLDER' })}
                            onChange={this.handleAttributionName}
                        />
                    </FormGroup>

                    <FormGroup>
                        <ControlLabel className="licensechooser-input-title">
                            <FormattedMessage id="LICENSECHOOSER.ATTRIBUTION-FIELD-URL"/>
                        </ControlLabel>
                        <FormControl
                            type="text"
                            value={this.props.attributionUrl}
                            placeholder={this.props.intl.formatMessage({ id: 'LICENSECHOOSER.ATTRIBUTION-FIELD-URL-PLACEHOLDER' })}
                            onChange={this.handleAttributionUrl}
                        />
                    </FormGroup>
                </div>
            );
        }

        return (
            <div>
                <ControlLabel className="licensechooser-group-title">
                    <FormattedMessage id="LICENSECHOOSER.RESTRICTION-LEVEL"/>
                </ControlLabel>
                <HelpIcon messageId="LICENSECHOOSER.RESTRICTION-LEVEL-HELP"/>
                <FormGroup>
                    <RadioGroup
                        name="restriction"
                        selectedValue={this.state.licenseType}
                        onChange={this.handleLicenseTypeChange}
                    >
                        <label className="radio-inline">
                            <Radio className="radio-inline" value="PUBLICDOMAIN"/>
                            <FormattedMessage id="LICENSECHOOSER.PUBLIC-DOMAIN"/>
                        </label>

                        <label className="radio-inline">
                            <Radio className="radio-inline" value="CC"/>
                            <FormattedMessage id="LICENSECHOOSER.CREATIVE-COMMONS"/>
                        </label>

                        <label className="radio-inline">
                            <Radio className="radio-inline" value="EDLL"/>
                            <FormattedMessage id="LICENSECHOOSER.EDLL"/>
                        </label>
                    </RadioGroup>
                </FormGroup>

                {publicDomain}
                {createCommons}
                {attributionFields}
            </div>
        );
    }
Example #18
Source File: Request.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 4 votes vote down vote up
export default function RequestFormModal({
    onClose = () => {},
    isShown = false,
    authLevel = {},
    maxRequest = DEFAULT_MAX_REQUEST,
    ...props
}) {

    // Auth level of the user
    const isCNIL = authLevel.isCNIL2 || authLevel.isCNIL1;

    const USER_TYPE_OPTIONS = [
        { value: 'A', label: 'cadastrapp.demandeinformation.type.A'},
        { value: 'P1', label: 'cadastrapp.demandeinformation.type.P1' },
        { value: 'P2', label: 'cadastrapp.demandeinformation.type.P2' },
        { value: 'P3', label: 'cadastrapp.demandeinformation.type.P3' }
    ];

    const [showReqByFields, setShowReqByFields] = useState(false);
    const [showRequestObj, setShowRequestObj] = useState(false);
    const [requestFormData, setRequestFormData] = useState(DEFAULT_REQUEST_OBJ);
    const [inValidField, setInValidField] = useState(true);
    const [availableRequest, setAvailableRequest] = useState(+maxRequest);
    const [checkingLimit, setCheckingLimit] = useState(false);

    useEffect(()=>{
        const {type, lastname, cni} = requestFormData;
        const isNotNormalUser = !isEmpty(type) && type !== "P3";  // P3 is normal user
        const isValidNormalUser = !isEmpty(cni) && type === "P3";

        setShowReqByFields(isNotNormalUser || isValidNormalUser); // Show/hide requestBy fields
        setShowRequestObj((isNotNormalUser && !!lastname.length) || isValidNormalUser); // Show/hide request object fields
    }, [requestFormData.cni, requestFormData.type, requestFormData.lastname]);

    // Check request limit based cni and type and set available request
    const checkRequestLimit = ({cni, type}) => {
        setCheckingLimit(true);
        checkRequestLimitation({cni, type}).then((data)=> {
            if (data.user) {
                // Use the fetched user data to populate the request form field
                setRequestFormData({
                    ...requestFormData, ...data.user,
                    firstname: data.user?.firstName || '',
                    lastname: data.user?.lastName || '',
                    codepostal: data.user?.codePostal || ''
                });
            }
            // Set available requests from the response, else set max request from configuration
            data.requestAvailable || data.requestAvailable === 0 ? setAvailableRequest(+data.requestAvailable) : setAvailableRequest(+maxRequest);
            setCheckingLimit(false);
        }).catch(()=>{
            setAvailableRequest(0);
            props.onError({
                title: "Error",
                message: "cadastrapp.demandeinformation.availableReqError"
            });
            setCheckingLimit(false);
        });
    };

    const [printRequest, setPrintRequest] = useState({});

    useEffect(() => {
        // Generate print params from form data
        setPrintRequest(formulatePrintParams(requestFormData));
    }, [requestFormData]);

    const onChange = (item) => {
        let formObj;
        if (item.value) {
            formObj = {...DEFAULT_REQUEST_OBJ, type: item.value};
        } else {
            const {name = '', value = ''} = item?.target || {};
            formObj = {...requestFormData, [name]: includes(['askby', 'responseby'], name) ? +value : value};
            name === "cni" && setCheckingLimit(true); // Set flag when checking for request limit
        }
        setRequestFormData(formObj);
    };

    const onBlur = ({target}) => {
        const {name = '', value = ''} = target || {};
        const trimmedValue = value.trim();
        setRequestFormData({...requestFormData, [name]: trimmedValue});

        // Trigger check request limit call
        if (name === "cni" && !isEmpty(requestFormData.type) && !isEmpty(trimmedValue) && trimmedValue.length > 2) {
            checkRequestLimit(requestFormData);
        }
    };

    const onCloseForm = () => { onClose(); setRequestFormData(DEFAULT_REQUEST_OBJ); setAvailableRequest(DEFAULT_MAX_REQUEST);};

    const formFields = [
        {
            value: requestFormData.cni,
            name: 'cni',
            label: <Message msgId={"cadastrapp.demandeinformation.cni"}/>,
            validation: requestFormData.type === 'P3' && isEmpty(requestFormData.cni) && "error"
        },
        {
            value: requestFormData.lastname,
            name: 'lastname',
            label: <Message msgId={"cadastrapp.demandeinformation.nom"}/>,
            validation: !isEmpty(requestFormData.type) && requestFormData.type !== 'P3' && isEmpty(requestFormData.lastname) && "error"
        },
        {
            value: requestFormData.firstname,
            name: 'firstname',
            label: <Message msgId={"cadastrapp.demandeinformation.prenom"}/>
        },
        {
            value: requestFormData.adress,
            name: 'adress',
            label: <Message msgId={"cadastrapp.demandeinformation.num_rue"}/>
        },
        {
            value: requestFormData.codepostal,
            name: 'codepostal',
            label: <Message msgId={"cadastrapp.demandeinformation.code_postal"}/>
        },
        {
            value: requestFormData.commune,
            name: 'commune',
            label: <Message msgId={"cadastrapp.demandeinformation.commune"}/>
        },
        {
            value: requestFormData.mail,
            name: 'mail',
            type: 'email',
            label: <Message msgId={"cadastrapp.demandeinformation.mail"}/>,
            validation: !isEmpty(requestFormData.mail) && !isValidEmail(requestFormData.mail) && "error"
        }
    ];

    const radioButtonGroup = {
        groupLabel: [
            {label: <Message msgId={"cadastrapp.demandeinformation.realise"}/>, name: 'askby' },
            {label: <Message msgId={"cadastrapp.demandeinformation.transmission"}/>, name: 'responseby'}
        ],
        groupField: [
            <Message msgId={"cadastrapp.demandeinformation.counter"}/>,
            <Message msgId={"cadastrapp.demandeinformation.mail"}/>,
            <Message msgId={"cadastrapp.demandeinformation.email"}/>
        ]
    };

    return (
        <Modal
            dialogClassName="cadastrapp-modal"
            show={isShown} onHide={onCloseForm}>
            <Modal.Header closeButton>
                <Modal.Title><Message msgId={'cadastrapp.demandeinformation.title'}/></Modal.Title>
            </Modal.Header>
            <Modal.Body className="request-modal-body">
                <div className="item-row">
                    <div className="label-col">
                        <ControlLabel><Message msgId={'cadastrapp.demandeinformation.type.demandeur'}/></ControlLabel>
                    </div>
                    <div className="form-col">
                        <Select name="type" value={requestFormData.type} onChange={onChange} options={USER_TYPE_OPTIONS}/>
                    </div>
                </div>
                {
                    formFields.map(({label, name, value, type = "text", validation = null}, index)=> (
                        <div className="item-row" key={index}>
                            <FormGroup validationState={validation}>
                                <div className="label-col">
                                    <ControlLabel>{label}</ControlLabel>
                                </div>
                                <div className="form-col">
                                    <FormControl
                                        disabled={isEmpty(requestFormData.type) || (name !== "cni" && requestFormData.type === 'P3' && isEmpty(requestFormData.cni))}
                                        value={value} name={name} onBlur={onBlur} onChange={onChange} type={type}
                                        bsSize="sm"
                                    />
                                </div>
                            </FormGroup>
                        </div>
                    ))
                }
                {
                    showReqByFields && radioButtonGroup.groupLabel.map(({label, name})=> (
                        <div className={"item-row"}>
                            <div className="label-col">
                                <ControlLabel>{label}</ControlLabel>
                            </div>
                            <div className="form-col">
                                <FormGroup>
                                    {radioButtonGroup.groupField.map((fieldLabel, index)=>
                                        <Radio onChange={onChange} checked={requestFormData[name] === index + 1} value={index + 1}  name={name} inline>
                                            {fieldLabel}
                                        </Radio>)}
                                </FormGroup>
                            </div>
                        </div>
                    ))
                }
                <hr/>
                {showRequestObj && !checkingLimit && <div className={"item-row"}>
                    <div className="request-obj-label">
                        <ControlLabel><Message msgId={"cadastrapp.demandeinformation.titre2"}/></ControlLabel>
                    </div>
                    <RequestObject
                        allow={isCNIL}
                        requestFormData={requestFormData}
                        setInValidField={setInValidField}
                        setRequestFormData={setRequestFormData}
                        setAvailableRequest={setAvailableRequest}
                        availableRequest={availableRequest}
                    />
                </div>
                }
            </Modal.Body>
            <Modal.Footer>
                <Button onClick={onCloseForm}><Message msgId={'cadastrapp.demandeinformation.annuler'}/></Button>
                <Button
                    disabled={!showRequestObj || checkingLimit || inValidField || props.loading}
                    onClick={()=>props.onPrintPDF(printRequest)}
                    className="print"
                >
                    {!props.allowDocument && props.loading ? (
                        <Spinner
                            spinnerName="circle"
                            noFadeIn
                            overrideSpinnerClassName="spinner"
                        />
                    ) : null}
                    <Message msgId={'cadastrapp.demandeinformation.imprimer'}/>
                </Button>
                <Button
                    disabled={isCNIL ? !props.allowDocument : true}
                    onClick={()=>props.onPrintPDF(null, 'Document')}
                    className="print"
                >
                    {props.allowDocument && props.loading ? (
                        <Spinner
                            spinnerName="circle"
                            noFadeIn
                            overrideSpinnerClassName="spinner"
                        />
                    ) : null}
                    <Message msgId={'cadastrapp.demandeinformation.generate.document'}/>
                </Button>
            </Modal.Footer>
        </Modal>);
}