Browse Source

edit plz fix formik

amenpunk 1 year ago
parent
commit
8e82fdff73
1 changed files with 237 additions and 224 deletions
  1. 237 224
      src/Components/Modal/EditPlaza.js

+ 237 - 224
src/Components/Modal/EditPlaza.js

@@ -1,8 +1,7 @@
1
-import React, { memo, useEffect, useCallback } from 'react';
1
+import React, { memo, useEffect, useCallback, useRef } from 'react';
2 2
 import { Modal } from 'react-bootstrap'
3
-import { useForm, Controller } from "react-hook-form";
4
-import { yupResolver } from '@hookform/resolvers/yup';
5 3
 import * as Yup from 'yup';
4
+import { useFormik, Form, FormikProvider } from 'formik';
6 5
 
7 6
 
8 7
 import { TabPanel } from './TabPanel'
@@ -55,7 +54,6 @@ async function savePuestoSuperior(input, auth) {
55 54
   return { id, nombre }
56 55
 }
57 56
 
58
-
59 57
 const plazeSchema = Yup.object({
60 58
   id: Yup.number(),
61 59
   nombrepuesto:
@@ -72,24 +70,44 @@ const plazeSchema = Yup.object({
72 70
 
73 71
 function Edit(props) {
74 72
 
75
-  const {setValue, getValues, reset, control, register, handleSubmit, formState: { errors } } = useForm({
76
-    resolver: yupResolver(plazeSchema),
77
-    defaultValues: {
73
+  // const { resetField, setFocus, setValue, getValues, reset, control, register, handleSubmit, formState: { errors } } = useForm({
74
+  //   resolver: yupResolver(plazeSchema),
75
+  //   defaultValues: {
76
+  //     id: 0,
77
+  //     nombrepuesto: 'mingtest',
78
+  //     puestosuperior: 0,
79
+  //     fecha: '01/01/2019',
80
+  //     notas: 'esto es un ejemplod e una nota',
81
+  //     aredepto: 1,
82
+  //     tests: []
83
+  //   }
84
+  // });
85
+
86
+  const formik = useFormik({
87
+    initialValues: {
78 88
       id: 0,
79
-      nombrepuesto: 'mingtest',
89
+      nombrepuesto: "",
80 90
       puestosuperior: 0,
81
-      fecha: '01/01/2019',
82
-      notas: 'esto es un ejemplod e una nota',
83 91
       aredepto: 1,
92
+      fecha: '01/01/2019',
93
+      notas: "",
84 94
       tests: []
85
-    }
95
+    },
96
+    onSubmit: (fields, { resetForm }) => {
97
+      console.log('submit values', fields)
98
+      saveEditPlaza(fields)
99
+    },
100
+    validationSchema: plazeSchema,
86 101
   });
87 102
 
88
-  const onSubmit = data => {
103
+
104
+  const { errors, touched, handleSubmit, getFieldProps, values, setValues } = formik;
105
+
106
+  const saveEditPlaza = data => {
89 107
 
90 108
     let body = {
91 109
       ...data,
92
-      fecha: new Date(data.fecha).toISOString()
110
+      fecha: new Date(data.fecha).toISOString(),
93 111
     }
94 112
 
95 113
     puestoMutation.mutate(body, {
@@ -113,6 +131,8 @@ function Edit(props) {
113 131
   let { visible, toggle } = props
114 132
 
115 133
   const [open, setOpen] = React.useState(false);
134
+  const [departamento, setDepartamento] = React.useState('');
135
+  const puestoref = useRef(null);
116 136
   const [tab, setTab] = React.useState(0);
117 137
   const [checklist, setChecklist] = React.useState([]);
118 138
   const [openSugg, setOpenSugg] = React.useState(false);
@@ -154,34 +174,46 @@ function Edit(props) {
154 174
       // let temp = getValues();
155 175
       // temp['puestosuperior'] = id
156 176
       // temp['puestosuperior_id'] = id
157
-      // reset({ ...temp, puestosuperior: id })
177
+      // reset({ ...temp, puestosuperior: id }, { keepDefaultValues: false, })
158 178
       // setDialogValueHook(value)
159
-      // reset({ ...temp, puestosuperior_id: id,puestosuperior:value.title })
160
-      // reset()
161
-      setValue('puestosuperior', parseInt( id ))
162
-      // setFocus("notas", { shouldSelect: true })
163
-      // // resetField('puestosuperior',{keepError:false})
164
-      //
179
+      // setValue('puestosuperior', parseInt(id))
180
+      // resetField('puestosuperior')
181
+      // let a = puestoref.current;
182
+      // a.focus();
183
+      // console.log(a)
184
+      // setValue('puestosuperior', id)
185
+      // reset({ ...temp, puestosuperior_id: id, puestosuperior: id }, {
186
+      //   keepErrors: true ,
187
+      //   keepDirty: true,
188
+      //   keepIsSubmitted: true,
189
+      //   keepTouched: true,
190
+      // })
165 191
 
166
-      // setDialogValueHook(value)
167 192
     }
193
+    // setFocus("puestosuperior_id",{shouldSelect:true})
168 194
     // console.log('SETTING:', value)
195
+    // console.log("final", getValues())
169 196
     setDialogValueHook(value)
170
-    console.log("final", getValues())
171 197
 
172
-  }, [setValue, getValues])
198
+  }, [])
199
+
200
+  const changeDepartamento = (event) => {
201
+    setDepartamento(event.target.value);
202
+  };
173 203
 
174 204
   const loading = openSugg && options.length === 0;
175 205
 
176 206
   const AutoCompleteChange = (event, newValue) => {
177
-    let temp = getValues();
178
-    console.log('newValue', temp, newValue)
179
-    temp['puestosuperior'] = newValue?.id;
207
+    // let temp = getValues();
208
+    // console.log('newValue', temp, newValue)
209
+    // temp['puestosuperior'] = newValue?.id;
180 210
     // reset(temp)
181 211
     // setDialogValue(newValue);
182 212
     // return;
183 213
     //this should be change
184
-    setValue('puestosuperior', newValue?.id)
214
+    // setValue('puestosuperior', newValue?.id)
215
+    setValues({ ...values, puestosuperior: newValue?.id })
216
+
185 217
     if (typeof newValue === 'string') {
186 218
       console.log('if1')
187 219
       setTimeout(() => {
@@ -205,8 +237,7 @@ function Edit(props) {
205 237
   }
206 238
 
207 239
   const addPrueba = (check, id) => {
208
-    let tests = getValues("tests")
209
-    console.log(tests)
240
+    let { tests } = values
210 241
     let temp;
211 242
     if (check) {
212 243
       temp = [...tests, { id }]
@@ -214,7 +245,8 @@ function Edit(props) {
214 245
       temp = tests.filter(test => test.id !== id);
215 246
     }
216 247
     setChecklist(temp.map(test => test.id))
217
-    setValue('tests', temp)
248
+    // setValue('tests', temp)
249
+    setValues({ ...values, tests: temp })
218 250
   };
219 251
 
220 252
   const getCategories = async () => {
@@ -240,7 +272,7 @@ function Edit(props) {
240 272
 
241 273
   useEffect(() => {
242 274
 
243
-    let current_id = getValues('id')
275
+    let current_id = values.id; // getValues('id')
244 276
 
245 277
     if (visible == null) return;
246 278
 
@@ -257,7 +289,7 @@ function Edit(props) {
257 289
             title: puestosuperior.nombre,
258 290
             id: puestosuperior.id
259 291
           })
260
-          reset({
292
+          setValues({
261 293
             ...response.data,
262 294
             aredepto: areadeptoplz_id,
263 295
             fecha: new Date(fecha),
@@ -286,7 +318,7 @@ function Edit(props) {
286 318
       active = false;
287 319
     };
288 320
 
289
-  }, [visible, auth, reset, loading, dialogValue, getValues, setDialogValue])
321
+  }, [visible, auth, loading, dialogValue, setDialogValue,setValues,values.id])
290 322
 
291 323
   const changeTab = (_event, newValue) => setTab(newValue);
292 324
 
@@ -354,203 +386,184 @@ function Edit(props) {
354 386
           </form>
355 387
         </Dialog>
356 388
 
357
-
358
-
359
-
360
-        <form onSubmit={handleSubmit(onSubmit)}>
361
-          <TabPanel value={tab} index={1}>
362
-            <Stack spacing={1}>
363
-              <Box style={{ paddingTop: 5, paddingLeft: 15 }}>
364
-                <Divider />
365
-                <h4 style={{ paddingTop: 10, paddingBottom: 10 }}>Seleciona los test a realizar</h4>
366
-                <Divider />
367
-                <FormGroup>
368
-                  {
369
-                    testsCatalog ?
370
-                      testsCatalog.data.map(test => (
371
-                        <FormControlLabel
372
-                          label={test.nombre}
373
-                          key={test.id}
374
-                          control={
375
-                            <Checkbox
376
-                              checked={checklist.includes((test.id))}
377
-                              onChange={(event) => addPrueba(event.target.checked, test.id)} />}
378
-                        />
379
-                      )) : null
380
-                  }
381
-                </FormGroup>
382
-              </Box>
383
-            </Stack>
384
-          </TabPanel>
385
-
386
-          <TabPanel value={tab} index={0} >
387
-            <Stack spacing={3}>
388
-
389
-              <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
390
-
391
-                <TextField
392
-                  name="nombrepuesto"
393
-                  label="Nombre"
394
-                  fullWidth
395
-                  helperText={errors.nombrepuesto?.message}
396
-                  error={Boolean(errors?.nombrepuesto)}
397
-                  {...register("nombrepuesto")} />
398
-
399
-
400
-                <FormControl fullWidth>
401
-                  <Controller
402
-                    helperText={errors.puestosuperior?.message}
403
-                    error={errors?.puestosuperior}
404
-                    name="puestosuperior"
405
-                    control={control}
406
-                    render={({ field }) =>
407
-                      <Autocomplete
408
-                        fullWidth
409
-                        value={dialogValue}
410
-                        onChange={AutoCompleteChange}
411
-                        open={openSugg}
412
-                        onOpen={() => {
413
-                          setOpenSugg(true);
414
-                        }}
415
-                        onClose={() => {
416
-                          setOpenSugg(false);
417
-                        }}
418
-                        isOptionEqualToValue={(option, value) => option.title === value.title}
419
-                        filterOptions={(options, params) => {
420
-                          const filtered = filter(options, params);
421
-
422
-                          if (params.inputValue !== '') {
423
-                            filtered.push({
424
-                              inputValue: params.inputValue,
425
-                              title: `Agregar "${params.inputValue}"`,
426
-                            });
427
-                          }
428
-
429
-                          return filtered;
430
-                        }}
431
-                        id="puesto_superior_autocomplete"
432
-                        options={options}
433
-                        loading={loading}
434
-                        getOptionLabel={(option) => {
435
-                          if (typeof option === 'string') {
436
-                            return option;
437
-                          }
438
-                          if (option.inputValue) {
439
-                            return option.inputValue;
440
-                          }
441
-                          return option.title;
442
-                        }}
443
-                        selectOnFocus
444
-                        clearOnBlur
445
-                        handleHomeEndKeys
446
-                        renderOption={(props, option) => <li key={option.id} {...props}>{option.title}</li>}
447
-                        freeSolo
448
-                        renderInput={(params) => (
449
-                          <TextField
450
-                            {...params}
451
-                            {...register('puestosuperior')}
452
-                            error={Boolean(errors.puestosuperior)}
453
-                            label="Puesto Superior"
454
-                            InputProps={{
455
-                              ...params.InputProps,
456
-                              onChange: (event) => {
457
-                                let title = event.target.value;
458
-                                console.log('titulo',title)
459
-                                setOptions([]);
460
-                                setDialogValue({
461
-                                  title: event.target.value,
462
-                                  id: '',
463
-                                });
464
-                              },
465
-                              endAdornment: (
466
-                                <React.Fragment>
467
-                                  {loading ? <CircularProgress color="inherit" size={20} /> : null}
468
-                                  {params.InputProps.endAdornment}
469
-                                </React.Fragment>
470
-                              ),
471
-                            }}
389
+        <FormikProvider style={{ paddingTop: 25 }} value={formik}>
390
+          <Form onSubmit={handleSubmit}>
391
+            <TabPanel value={tab} index={1}>
392
+              <Stack spacing={1}>
393
+                <Box style={{ paddingTop: 5, paddingLeft: 15 }}>
394
+                  <Divider />
395
+                  <h4 style={{ paddingTop: 10, paddingBottom: 10 }}>Seleciona los test a realizar</h4>
396
+                  <Divider />
397
+                  <FormGroup>
398
+                    {
399
+                      testsCatalog ?
400
+                        testsCatalog.data.map(test => (
401
+                          <FormControlLabel
402
+                            label={test.nombre}
403
+                            key={test.id}
404
+                            control={
405
+                              <Checkbox
406
+                                checked={checklist.includes((test.id))}
407
+                                onChange={(event) => addPrueba(event.target.checked, test.id)} />}
472 408
                           />
473
-                        )}
474
-
475
-                      />
476
-
409
+                        )) : null
477 410
                     }
478
-                  >
479
-                  </Controller>
480
-                </FormControl>
481
-
411
+                  </FormGroup>
412
+                </Box>
482 413
               </Stack>
483
-
484
-              <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
485
-
486
-                <FormControl fullWidth>
487
-                  <InputLabel id="demo-simple-select-label2">Departamento</InputLabel>
488
-                  <Controller
489
-                    helperText={errors.aredepto?.message}
490
-                    error={Boolean(errors?.aredepto)}
491
-                    name="aredepto"
492
-                    control={control}
493
-                    render={({ field }) =>
494
-                      <Select {...field}>
495
-                        {
496
-                          categories ?
497
-                            categories.data.map(cate => {
498
-                              return (
499
-                                <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
500
-                              )
501
-                            })
502
-                            : <MenuItem value={1}>hola</MenuItem>
414
+            </TabPanel>
415
+
416
+            <TabPanel value={tab} index={0} >
417
+              <Stack spacing={3}>
418
+
419
+                <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
420
+
421
+                  <TextField
422
+                    name="nombrepuesto"
423
+                    label="Nombre"
424
+                    fullWidth
425
+                    helperText={errors.nombrepuesto?.message}
426
+                    error={Boolean(errors?.nombrepuesto)}
427
+                    {...getFieldProps("nombrepuesto")} />
428
+
429
+
430
+                  <FormControl fullWidth>
431
+                    <Autocomplete
432
+                      fullWidth
433
+                      value={dialogValue}
434
+                      onChange={AutoCompleteChange}
435
+                      open={openSugg}
436
+                      onOpen={() => {
437
+                        setOpenSugg(true);
438
+                      }}
439
+                      onClose={() => {
440
+                        setOpenSugg(false);
441
+                      }}
442
+                      isOptionEqualToValue={(option, value) => option.title === value.title}
443
+                      filterOptions={(options, params) => {
444
+                        const filtered = filter(options, params);
445
+
446
+                        if (params.inputValue !== '') {
447
+                          filtered.push({
448
+                            inputValue: params.inputValue,
449
+                            title: `Agregar "${params.inputValue}"`,
450
+                          });
503 451
                         }
504
-                      </Select>
505
-                    }>
506
-                  </Controller>
507
-                </FormControl>
508
-
509
-                <LocalizationProvider dateAdapter={DateFnsUtils}>
510
-                  <Controller
511
-                    name="fecha"
512
-                    control={control}
513
-                    render={({ field }) =>
514
-                      <DesktopDatePicker
515
-                        {...field}
516
-                        helperText={errors.fecha?.message}
517
-                        error={Boolean(errors?.fecha)}
518
-                        label="Fecha Creación"
519
-                        fullWidth
520
-                        inputFormat="dd/MM/yyyy"
521
-                        renderInput={(params) => <TextField {...params} helperText={errors.fecha?.message} />} />}
522
-                  >
523
-                  </Controller>
524
-                </LocalizationProvider>
525
-              </Stack>
526 452
 
527
-              <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
528
-                <TextField
529
-                  helperText={errors.notas?.message}
530
-                  error={Boolean(errors?.notas)}
531
-                  name="notas"
532
-                  multiline
533
-                  rows={4}
534
-                  label="Notas"
535
-                  fullWidth
536
-                  type="text"
537
-                  {...register("notas")}
538
-                />
453
+                        return filtered;
454
+                      }}
455
+                      id="puesto_superior_autocomplete"
456
+                      options={options}
457
+                      loading={loading}
458
+                      getOptionLabel={(option) => {
459
+                        if (typeof option === 'string') {
460
+                          return option;
461
+                        }
462
+                        if (option.inputValue) {
463
+                          return option.inputValue;
464
+                        }
465
+                        return option.title;
466
+                      }}
467
+                      selectOnFocus
468
+                      // clearOnBlur
469
+                      // handleHomeEndKeys
470
+                      renderOption={(props, option) => <li key={option.id} {...props}>{option.title}</li>}
471
+                      freeSolo
472
+                      renderInput={(params) => (
473
+                        <TextField
474
+                          {...params}
475
+                          {...getFieldProps('puestosuperior')}
476
+                          error={Boolean(errors.puestosuperior)}
477
+                          label="Puesto Superior"
478
+                          InputProps={{
479
+                            ...params.InputProps,
480
+                            onChange: (event) => {
481
+                              let title = event.target.value;
482
+                              console.log('titulo', title)
483
+                              setOptions([]);
484
+                              setDialogValue({
485
+                                title: title,
486
+                                id: '',
487
+                              });
488
+                            },
489
+                            endAdornment: (
490
+                              <React.Fragment>
491
+                                {loading ? <CircularProgress color="inherit" size={20} /> : null}
492
+                                {params.InputProps.endAdornment}
493
+                              </React.Fragment>
494
+                            ),
495
+                          }}
496
+                        />
497
+                      )}
498
+
499
+                    />
500
+                  </FormControl>
501
+
502
+                </Stack>
503
+
504
+                <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
505
+
506
+                  <FormControl fullWidth>
507
+                    <InputLabel id="demo-simple-select-label2">Departamento</InputLabel>
508
+                    <Select
509
+                      value={departamento}
510
+                      label="Departamento"
511
+                      onChange={changeDepartamento}
512
+                      {...getFieldProps('aredepto')}
513
+                      error={Boolean(touched.aredepto && errors.aredepto)}>
514
+                      {
515
+                        categories ?
516
+                          categories.data.map(cate => {
517
+                            return (
518
+                              <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
519
+                            )
520
+                          })
521
+                          : <MenuItem value={1}>hola</MenuItem>
522
+                      }
523
+                    </Select>
524
+                  </FormControl>
525
+
526
+                  <LocalizationProvider dateAdapter={DateFnsUtils}>
527
+                    <DesktopDatePicker
528
+                      helperText={errors.fecha?.message}
529
+                      error={Boolean(errors?.fecha)}
530
+                      label="Fecha Creación"
531
+                      fullWidth
532
+                      inputFormat="dd/MM/yyyy"
533
+                      renderInput={(params) => <TextField {...params} helperText={errors.fecha?.message} />}
534
+                    />
535
+                  </LocalizationProvider>
536
+                </Stack>
537
+
538
+                <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
539
+                  <TextField
540
+                    helperText={errors.notas?.message}
541
+                    error={Boolean(errors?.notas)}
542
+                    name="notas"
543
+                    multiline
544
+                    rows={4}
545
+                    label="Notas"
546
+                    fullWidth
547
+                    type="text"
548
+                    {...getFieldProps("notas")}
549
+                  />
550
+                </Stack>
539 551
               </Stack>
540
-            </Stack>
541
-          </TabPanel>
542
-
543
-          <Modal.Footer>
544
-            <Button
545
-              type="submit"
546
-              className="registerBtn"
547
-              variant="contained"
548
-              sx={{ mt: 1, mr: 1 }} >
549
-              {'Actualizar'}
550
-            </Button>
551
-          </Modal.Footer>
552
-
553
-        </form>
552
+            </TabPanel>
553
+
554
+            <Modal.Footer>
555
+              <Button
556
+                ref={puestoref}
557
+                type="submit"
558
+                className="registerBtn"
559
+                variant="contained"
560
+                sx={{ mt: 1, mr: 1 }} >
561
+                {'Actualizar'}
562
+              </Button>
563
+            </Modal.Footer>
564
+
565
+          </Form>
566
+        </FormikProvider>
554 567
 
555 568
       </Modal.Body>
556 569
       <Backdrop