import { useState, Fragment } from 'react'; import api from '../../utils/api'; import 'notyf/notyf.min.css'; const EditFormFunction = (props) => { const [inputsArray, setInputsArray] = useState(props.functionInfo.utilizationForm || []); const addInput = () => { const newInputsArray = [...inputsArray]; newInputsArray.push({ name: "", label: "", placeholder: "", type: "text" }); setInputsArray(newInputsArray); } const addOption = (event) => { const newInputsArray = [...inputsArray]; const index = event.target.id.split('-')[1]; const inputObject = newInputsArray[index]; inputObject.options.push({ name: "", value: "" }); setInputsArray(newInputsArray); } const handleChangeOption = (inputIndex, optionIndex, event) => { const newInputsArray = [...inputsArray]; const inputObject = newInputsArray[inputIndex]; const optionObject = inputObject.options[optionIndex]; optionObject[event.target.name] = event.target.value; setInputsArray(newInputsArray); } const handleChangeInput = (event) => { const newInputsArray = [...inputsArray]; const index = event.target.id.split('-')[1]; const inputObject = newInputsArray[index]; inputObject[event.target.name] = event.target.value; if (event.target.value === "select") { inputObject.options = []; } setInputsArray(newInputsArray); } const handleSubmit = async (event) => { event.preventDefault(); let Notyf; if (typeof window != 'undefined') { Notyf = require('notyf'); } const notyf = new Notyf.Notyf({ duration: 5000 }); try { await api.put(`/admin/functions/form/${props.functionInfo.id}`, { form: inputsArray }, { headers: { 'Authorization': props.user.token } }); notyf.success('Sauvegardé!'); } catch (error) { notyf.error('Erreur!'); } } const handleRemoveInput = (event) => { const newInputsArray = [...inputsArray]; const index = event.target.id.split('-')[1]; newInputsArray.splice(index, 1); setInputsArray(newInputsArray); } const handleRemoveOption = (inputIndex, optionIndex) => { const newInputsArray = [...inputsArray]; const inputObject = newInputsArray[inputIndex]; const optionsArray = inputObject.options; optionsArray.splice(optionIndex, 1); setInputsArray(newInputsArray); } return (
{(inputsArray.length > 0) &&
} {inputsArray.map((input, index) => { return (


{(input.type !== "select") &&
} {(input.type === "select") &&
{input.options.map((option, optionIndex) => { return (
handleChangeOption(index, optionIndex, event)} value={option.name} id={`optionName-${optionIndex}-${index}`} name="name" type="text"className="form-control" placeholder="Nom de l'option" />
handleChangeOption(index, optionIndex, event)} value={option.value} id={`optionValue-${optionIndex}-${index}`} name="value" type="text"className="form-control" placeholder="Valeur de l'option" />
); })}
}
); })}
); } export default EditFormFunction;