@material-ui/core#Switch JavaScript Examples

The following examples show how to use @material-ui/core#Switch. 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: form-util.js    From surveillance-forms with MIT License 7 votes vote down vote up
StatefulSwitch = ({ field }) => {
  const { label, onChange } = field;
  const [value, setValue] = useState(field.value || false);

  const handleChange = () => {
    const newValue = !value;
    setValue(newValue);

    if (onChange) {
      onChange(newValue);
    }
  };

  const switchLabel = value ? field.onLabel : field.offLabel;

  return (
    <Box display="flex" alignItems="center">
      <Box
        style={{
          borderRadius: "50px",
          border: "1px solid #ccc",
          margin: "5px 10px 5px 0",
        }}
      >
        <Switch
          checked={value}
          onChange={handleChange}
          name="checkedA"
          inputProps={{ "aria-label": "secondary checkbox" }}
        />
        <Typography variant="caption" style={{ opacity: 0.5, marginRight: 10 }}>
          {switchLabel}
        </Typography>
      </Box>
      <Typography>{label}</Typography>
    </Box>
  );
}
Example #2
Source File: FancySwitch.js    From Website with MIT License 6 votes vote down vote up
FancySwitch = withStyles({
	root: {
		padding: 7,
	},
	thumb: {
		width: 24,
		height: 24,
		backgroundColor: "#fff",
		boxShadow: "0 0 12px 0 rgba(0,0,0,0.08), 0 0 8px 0 rgba(0,0,0,0.12), 0 0 4px 0 rgba(0,0,0,0.38)",
	},
	switchBase: {
		color: "rgba(0,0,0,0.38)",
		padding: 7,
	},
	track: {
		borderRadius: 20,
		backgroundColor: blueGrey[300],
	},
	checked: {
		"& $thumb": {
			backgroundColor: "#fff",
		},
		"& + $track": {
			opacity: "1 !important",
		},
	},
})(props => <Switch color="primary" {...props}/>)
Example #3
Source File: index.js    From Artion-Client with GNU General Public License v3.0 6 votes vote down vote up
PurpleSwitch = withStyles({
  switchBase: {
    color: '#1969FF',
    '&$checked': {
      color: '#1969FF',
    },
    '&$checked + $track': {
      backgroundColor: '#1969FFAA',
    },
  },
  checked: {},
  track: {},
})(Switch)
Example #4
Source File: SwitchShowDollar.js    From lrc-staking-dapp with MIT License 6 votes vote down vote up
SwitchShowDollar = React.memo(({ classes, isShowDollar, onSwitch }) => (
  <div className={classes.divTopRight}>
    { isShowDollar
      ? (<FontAwesomeIcon className={classes.iconDollar} icon={['fas', 'dollar-sign']} />)
      : (<img alt="Loopring logo" className={classes.loopringLogo} src={lrc} height="16px" />)}
    <Switch
      checked={isShowDollar}
      onChange={() => onSwitch(!isShowDollar)}
      value="checkedA"
      color="primary"
    />
  </div>
))
Example #5
Source File: Switcher.js    From web with GNU General Public License v3.0 6 votes vote down vote up
Switcher = ({ checked, disabled, label, name, onChange }) => {
  return (
    <SwitcherWrapper>
      <FormControlLabel
        disabled={disabled}
        control={
          <Switch
            size="medium"
            checked={checked}
            onChange={onChange}
            name={name}
          />
        }
        label={label}
      />
    </SwitcherWrapper>
  );
}
Example #6
Source File: app-header.spec.js    From horondi_client_fe with MIT License 6 votes vote down vote up
describe('Test for the app-header component', () => {
  it('It should simulate click on switch in the app-header component', () => {
    wrapper = shallow(<AppHeader />);
    const switchTheme = wrapper.find(Switch);
    switchTheme.simulate('click', {
      target: {
        checked: true
      }
    });
    expect(wrapper).toBeDefined();
  });
});
Example #7
Source File: index.js    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
function Toggle(props) {
    const {
        leftLabel = 'Correct',
        rightLabel = 'Wrong',
        isCorrect = true,
        onToggle,
    } = props;

    return (
        <div className="togglerSwitch">
            <label>{leftLabel}</label>
            <Switch
                onChange={onToggle}
                checked={isCorrect}
                color="default"
            />
            <label>{rightLabel}</label>
        </div>
    );
}
Example #8
Source File: ArmingFlagsView.js    From Nemesis with GNU General Public License v3.0 5 votes vote down vote up
render() {
    return (
      <React.Fragment>
        <Typography variant="h5">
          <FormattedMessage id="pfc.armingflags.title" />
        </Typography>
        <List>
          {this.state.armingFlags.map(flag => (
            <Chip
              onClick={flag.onClick}
              key={flag.label}
              style={{ margin: 4 }}
              label={<FormattedMessage id={flag.label} />}
            />
          ))}
        </List>
        <FormGroup component="fieldset">
          {this.state.debug && (
            <FormControlLabel
              control={
                <Switch
                  checked={this.state.showDebug}
                  onChange={(event, showDebug) => {
                    this.setState({ showDebug });
                  }}
                />
              }
              label={<FormattedMessage id="info.show-debug" />}
            />
          )}
          {this.state.showDebug && (
            <List>
              {this.state.debug.map((debugVal, index) => {
                return (
                  <ListItem className="debug-item" key={index}>
                    DEBUG {index}: {debugVal}
                  </ListItem>
                );
              })}
            </List>
          )}
        </FormGroup>
      </React.Fragment>
    );
  }
Example #9
Source File: PreliminaryScores.js    From dipact with GNU General Public License v3.0 5 votes vote down vote up
render() {
		const { classes } = this.props;
		if (!this.state.open) {
			return "";
		}
		return (
			<Dialog
				onEntered={helpers.genOnback(this.close)}
				open={this.state.open}
				disableBackdropClick={false}
				classes={{
					paper: classes.paper,
				}}
				onClose={this.close}
			>
				<DialogTitle>Scores</DialogTitle>
				<DialogContent>
					<Typography>
						If the game ends in a draw, points will be divided as
						below (based on the{" "}
						<a href="http://windycityweasels.org/tribute-scoring-system/">
							Tribute
						</a>{" "}
						system).
					</Typography>
					Score{" "}
					<Switch
						checked={this.state.show !== "score"}
						onChange={(ev) => {
							this.setState({
								show: ev.target.checked ? "scs" : "score",
							});
						}}
					/>{" "}
					Supply centers
					<canvas id="score-chart" height="520" width="420"></canvas>
					<DialogActions className={classes.dialogActions}>
						<Button onClick={this.close} color="primary">
							Close
						</Button>
					</DialogActions>
				</DialogContent>
			</Dialog>
		);
	}
Example #10
Source File: index.js    From Codelabz with Apache License 2.0 5 votes vote down vote up
UserPassword = () => {
  const classes = useStyles();

  return (
    <Card className={classes.card}>
      <Box
        component="form"
        noValidate
        sx={{
          display: "flex",
          flexDirection: "column",
        }}
      >
        <Box style={{ marginBottom: "5px" }}>
          <Typography className={classes.text}>Old password</Typography>
          <Input type="password" className={classes.input} />
        </Box>
        <Box style={{ margin: "5px 0" }}>
          <Typography className={classes.text}>New password</Typography>
          <Input type="password" className={classes.input} />
        </Box>
        <Box style={{ margin: "5px 0" }}>
          <Typography className={classes.text}>Confirm new password</Typography>
          <Input type="password" className={classes.input} />
        </Box>
        <Button className={classes.button}>Update Password</Button>
        <Box className={classes.row}>
          <Typography className={classes.text}>Logout</Typography>
          <Typography
            className={classes.text}
            style={{ marginRight: 40, color: "#0075AD" }}
          >
            Logout of all other browsers
          </Typography>
        </Box>
        <Box className={classes.row}>
          <Typography className={classes.text}>Login security</Typography>
          <Box style={{ display: "flex", alignItems: "center" }}>
            <Typography className={classes.text}>
              Require email verification
            </Typography>
            <Switch color="primary" />
          </Box>
        </Box>
      </Box>
    </Card>
  );
}
Example #11
Source File: PopupPage.js    From spl-token-wallet with Apache License 2.0 5 votes vote down vote up
function ApproveConnectionForm({ origin, onApprove }) {
  const wallet = useWallet();
  const { accounts, hardwareWalletAccount } = useWalletSelector();
  // TODO better way to do this
  const account = accounts
    .concat([hardwareWalletAccount])
    .find((account) => account && account.address.equals(wallet.publicKey));
  const classes = useStyles();
  const [autoApprove, setAutoApprove] = useState(false);
  let [dismissed, setDismissed] = useLocalStorageState(
    'dismissedAutoApproveWarning',
    false,
  );
  return (
    <Card>
      <CardContent>
        <Typography variant="h6" component="h1" gutterBottom>
          Allow this site to access your Solana account?
        </Typography>
        <div className={classes.connection}>
          <Typography>{origin}</Typography>
          <ImportExportIcon fontSize="large" />
          <Typography>{account.name}</Typography>
          <Typography variant="caption">
            ({wallet.publicKey.toBase58()})
          </Typography>
        </div>
        <Typography>Only connect with sites you trust.</Typography>
        <Divider className={classes.divider} />
        <FormControlLabel
          control={
            <Switch
              checked={autoApprove}
              onChange={() => setAutoApprove(!autoApprove)}
              color="primary"
            />
          }
          label={`Automatically approve transactions from ${origin}`}
        />
        {!dismissed && autoApprove && (
          <SnackbarContent
            className={classes.warningContainer}
            message={
              <div>
                <span className={classes.warningTitle}>
                  <WarningIcon className={classes.warningIcon} />
                  Use at your own risk.
                </span>
                <Typography className={classes.warningMessage}>
                  This setting allows sending some transactions on your behalf
                  without requesting your permission for the remainder of this
                  session.
                </Typography>
              </div>
            }
            action={[
              <Button onClick={() => setDismissed('1')}>I understand</Button>,
            ]}
            classes={{ root: classes.snackbarRoot }}
          />
        )}
      </CardContent>
      <CardActions className={classes.actions}>
        <Button onClick={window.close}>Cancel</Button>
        <Button
          color="primary"
          onClick={() => onApprove(autoApprove)}
          disabled={!dismissed && autoApprove}
        >
          Connect
        </Button>
      </CardActions>
    </Card>
  );
}
Example #12
Source File: app-header.js    From horondi_client_fe with MIT License 5 votes vote down vote up
AppHeader = () => {
  const { t } = useTranslation();
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [lightMode, setLightMode] = useContext(ThemeContext);
  const [sticky, setSticky] = useState(false);
  const theme = getFromLocalStorage('theme');
  const styles = useStyles();
  const appStyles = useAppStyles();

  const Header = clsx({
    [styles.header]: true,
    [styles.sticky]: sticky
  });

  useLayoutEffect(() => {
    let lastScrollTop = 0;
    window.addEventListener('scroll', () => {
      const currPoint = window.scrollY;
      currPoint > lastScrollTop ? setSticky(true) : setSticky(false);
      lastScrollTop = currPoint <= 0 ? 0 : currPoint;
    });
  }, []);

  const handleChangeTheme = (e) => {
    e.target.checked = !e.target.checked;
    setLightMode(!lightMode);
    setToLocalStorage('theme', !lightMode ? LIGHT_THEME : DARK_THEME);
  };

  return (
    <div className={styles.root}>
      <AppBar position='static' className={Header}>
        <Toolbar className={`${appStyles.containerWideApp} ${styles.upperToolbar}`} disableGutters>
          <Typography>{t('header.workingDays')}</Typography>
          <div className={styles.theme}>
            <Typography>{t('header.lightTheme')}</Typography>
            <Switch checked={theme === 'dark'} onClick={handleChangeTheme} />
            <Typography>{t('header.darkTheme')}</Typography>
          </div>
          <div className={styles.language}>
            <Language />
          </div>
          <div className={styles.currency}>
            <CurrencyComponent />
          </div>
          <PhoneLink href='tel:+380961737361' className={styles.callUs} variant='body1'>
            {t('header.callUs')}
          </PhoneLink>
        </Toolbar>
        <Toolbar className={`${appStyles.containerWideApp} ${styles.bottomToolbar}`} disableGutters>
          <BurgerMenu className={styles.menuButton} onClick={() => setIsMenuOpen(true)}>
            <MenuIcon />
          </BurgerMenu>
          <Typography variant='h5'>
            <Link to='/' className={styles.logo}>
              {HORONDI.toUpperCase()}
            </Link>
          </Typography>
          <HeaderRightBar setIsMenuOpen={setIsMenuOpen} />
        </Toolbar>
      </AppBar>
      <div className={styles.headerspace} />
      <Sidebar setIsMenuOpen={setIsMenuOpen} isMenuOpen={isMenuOpen} />
    </div>
  );
}
Example #13
Source File: navBar.js    From urlShortner with GNU General Public License v3.0 5 votes vote down vote up
export default function NavBar() {
  const classes = useStyles();
  const [theme, setTheme] = useState(
    localStorage.getItem('selected-theme') === 'dark' ? 'dark' : 'light',
  );
  const themeToggler = () => {
    if (theme === 'light') {
      setTheme('dark');
      localStorage.setItem('selected-theme', 'dark');
    } else {
      setTheme('light');
      localStorage.setItem('selected-theme', 'light');
    }
  };

  useEffect(() => {
    let darkVal = localStorage.getItem('selected-theme');
    if (darkVal) {
      setTheme(darkVal);
    } else {
      setTheme('light');
      localStorage.setItem('selected-theme', 'light');
    }
  }, []);

  return (
    <ThemeProvider theme={theme === 'light' ? lightTheme : darkTheme}>
      <GlobalStyles />
      <div className={classes.root}>
        <AppBar
          position="fixed"
          color="inherit"
          style={{ backgroundColor: 'inherit', paddingRight: 0 }}
          className="fill"
          id="navbar"
        >
          <Container fixed>
            <div>
              <GitHubRibbon href="https://github.com/developer-student-club-thapar/urlShortner" />
            </div>
            <Toolbar>
              <Box className={classes.title}>
                <img
                  src={logo}
                  className={classes.logo}
                  alt="logo"
                  id="logo"
                  onClick={() => {
                    window.open('https://dsctiet.tech/');
                  }}
                />
                <Hidden smDown>
                  <Typography
                    variant="h6"
                    id="dsc"
                    onClick={() => {
                      window.open('https://dsctiet.tech/');
                    }}
                  >
                    {' '}
                    &nbsp; DSC TIET
                  </Typography>
                </Hidden>
              </Box>
              <Box className={classes.titleCenter}>
                <Typography variant="h6" id="url">
                  URL Shortener
                </Typography>
              </Box>
              <Box className={classes.toggle}>
                <Switch onClick={themeToggler} color="secondary" />
              </Box>
            </Toolbar>
          </Container>
        </AppBar>
      </div>
    </ThemeProvider>
  );
}
Example #14
Source File: AppHeader.js    From mentors-website with MIT License 5 votes vote down vote up
AppHeader = ({darkMode, ModeChange}) => {
    const classes = useStyles();

    return (
        <AppBar position="static" className={classes.appBar}>
            <Container maxWidth='lg'>
                <Toolbar disableGutters className={classes.toolbar_container}>

                    <MUILink href="/" title="CodeHood Mentors" className={classes.brand}>
                        <img src={CodeHoodLogo} alt="Codehood" />
                        <Hidden only={['xs', 'sm']}>
                            <Typography
                                variant={window.innerWidth < 637 ? "h6" : "h4"}
                                className={classes.title}
                            >
                                Mentors
                            </Typography>
                        </Hidden>
                    </MUILink>

                    <FormControlLabel
                        control={
                            <Switch
                                name="switch_dark_mode"
                                checked={darkMode}
                                onChange={ModeChange}
                                aria-label={darkMode ? "Light Mode" : "Dark Mode"}
                                color='default'
                            />
                        }
                        label={
                            darkMode ? (
                                <LightIcon htmlColor='#ffffff' />
                            ) : (
                                <DarkIcon htmlColor='#ffffff' />
                            )
                        }
                    />
                    
                </Toolbar>
            </Container>
        </AppBar>
    )
}
Example #15
Source File: MainSettings.js    From Interceptor with MIT License 5 votes vote down vote up
render() {
    //console.log("Rendering MainSettings");
    return (
      <Dialog
        open={this.props.show}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Main settings</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} direction="column" alignItems="flex-start">
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="ws_url">WebSocket URL</InputLabel>
                <Input
                  id="ws_url"
                  value={this.state.ws_url}
                  onChange={event => this.setState({ ws_url: event.target.value })}
                  aria-describedby="ws_url-helper-text"
                  inputProps={{
                    'aria-label': 'WebSocket URL',
                  }}
                />
                <FormHelperText id="ws_url-helper-text">Tethered WiFi ws://192.168.43.1:8989</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="rateHz">Render rate</InputLabel>
                <Input
                  id="rateHz"
                  value={this.state.rateHz}
                  onChange={event => this.setState({ rateHz: Math.min(Math.max(parseInt(event.target.value), 0.5), 20) })}
                  endAdornment={<InputAdornment position="end">Hz</InputAdornment>}
                  aria-describedby="rateHz-helper-text"
                  inputProps={{
                    'aria-label': 'Render rate',
                  }}
                />
                <FormHelperText id="rateHz-helper-text">Min: 0.5, Max: 20</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControlLabel
                control={<Switch checked={this.state.dark_theme} onChange={() => this.setState({ dark_theme: !this.state.dark_theme })} name="dark_theme" />}
                label="Dark theme"
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => this.props.setSettings(this.state.ws_url, this.state.rateHz, this.state.dark_theme)} color="default">
            Save
        </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #16
Source File: GraphSettings.js    From Interceptor with MIT License 5 votes vote down vote up
render() {
    //console.log("Rendering GraphSettings");
    return (
      <Dialog
        open={this.props.show}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Graphs settings</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} direction="column" alignItems="flex-start">
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="cols">Graph columns</InputLabel>
                <Input
                  id="cols"
                  value={this.state.cols}
                  onChange={event => this.setState({ cols: Math.min(Math.max(parseInt(event.target.value), 1), 12) })}
                  aria-describedby="cols-helper-text"
                  inputProps={{
                    'aria-label': 'Graph columns',
                  }}
                />
                <FormHelperText id="cols-helper-text">Max: 12</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="rateHz">Render rate</InputLabel>
                <Input
                  id="rateHz"
                  value={this.state.rateHz}
                  onChange={event => this.setState({ rateHz: Math.min(Math.max(parseInt(event.target.value), 0.5), 20) })}
                  endAdornment={<InputAdornment position="end">Hz</InputAdornment>}
                  aria-describedby="rateHz-helper-text"
                  inputProps={{
                    'aria-label': 'Render rate',
                  }}
                />
                <FormHelperText id="rateHz-helper-text">Min: 0.5, Max: 20</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="max_datapoints">Max data points</InputLabel>
                <Input
                  id="max_datapoints"
                  value={this.state.max_datapoints}
                  onChange={event => this.setState({ max_datapoints: Math.min(Math.max(parseInt(event.target.value), 20), 10000) })}
                  aria-describedby="max_datapoints-helper-text"
                  inputProps={{
                    'aria-label': 'Max data points',
                  }}
                />
                <FormHelperText id="max_datapoints-helper-text">Max: 10000</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControlLabel
                control={<Switch checked={this.state.webgl} onChange={() => this.setState({ webgl: !this.state.webgl })} name="webGL" />}
                label="WebGL support"
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => this.props.setSettings(this.state.cols, this.state.rateHz, this.state.max_datapoints, this.state.webgl)} color="default">
            Save
        </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #17
Source File: header.js    From vote-incentives with GNU General Public License v3.0 5 votes vote down vote up
StyledSwitch = withStyles((theme) => ({
  root: {
    width: 58,
    height: 32,
    padding: 0,
    margin: theme.spacing(1),
  },
  switchBase: {
    padding: 1,
    '&$checked': {
      transform: 'translateX(28px)',
      color: '#212529',
      '& + $track': {
        backgroundColor: '#ffffff',
        opacity: 1,
      },
    },
    '&$focusVisible $thumb': {
      color: '#ffffff',
      border: '6px solid #fff',
    }
  },
  thumb: {
    width: 24,
    height: 24,
  },
  track: {
    borderRadius: 32 / 2,
    border: `1px solid #212529`,
    backgroundColor: '#212529',
    opacity: 1,
    transition: theme.transitions.create(['background-color', 'border']),
  },
  checked: {},
  focusVisible: {},
}))(({ classes, ...props }) => {
  return (
    <Switch
      focusVisibleClassName={classes.focusVisible}
      disableRipple
      classes={{
        root: classes.root,
        switchBase: classes.switchBase,
        thumb: classes.thumb,
        track: classes.track,
        checked: classes.checked,
      }}
      {...props}
    />
  );
})
Example #18
Source File: AboutPage.js    From beluga with GNU General Public License v3.0 5 votes vote down vote up
function AboutPage(props) {
  const { storeConfig, handleChange } = props;
  const [aboutText, setAboutText] = useState("");
  const [savedToFile, setSavedToFile] = useState(false);

  useState(() => {
    if (!storeConfig.about_page) return;

    fetch('/about-text/')
      .then(res => res.json())
      .then(results => {
        if (results.error) return;
        else setAboutText(results);
      })
  }, [storeConfig.about_page])

  const saveText = () => {
    fetch("/about-text/", {
        method: 'POST',
        headers: new Headers({ 'content-type': 'application/json' }),
        body: JSON.stringify({ text: aboutText })
      }).then((response) => response.json())
      .then(result => {
        if (result.success)
          setSavedToFile(true);
      });
  }

  return (
    <div>
      <Switch size="small" 
        checked={storeConfig.about_page}
        onChange={e => handleChange("about_page", e.target.checked, true, true)}
      />
      Display an "About" Page
      { storeConfig.about_page && (
        <div>
          <TextField
            label="About Page Text"
            value={aboutText}
            multiline={true}
            onChange={(e) => {
              setAboutText(e.target.value)
              setSavedToFile(false);
            }}
            style={{ margin: "40px 0"}}
            variant="outlined"
            rows="3"
            fullWidth
          />
          { savedToFile ? (
            <Link to="/about" style={{ textDecoration: "none" }}>
              <Button variant="contained" color="secondary"
                onClick={saveText}
              >
                View On Site
              </Button>
            </Link>
          ) : (
            <Button variant="contained" color="primary"
              onClick={saveText}
            >
              Save
            </Button>
          )}
        </div>
      )}
    </div>
  );
}
Example #19
Source File: navigation.js    From vote-incentives with GNU General Public License v3.0 5 votes vote down vote up
StyledSwitch = withStyles((theme) => ({
  root: {
    width: 58,
    height: 32,
    padding: 0,
    margin: theme.spacing(1),
  },
  switchBase: {
    padding: 1,
    '&$checked': {
      transform: 'translateX(28px)',
      color: '#212529',
      '& + $track': {
        backgroundColor: '#ffffff',
        opacity: 1,
      },
    },
    '&$focusVisible $thumb': {
      color: '#ffffff',
      border: '6px solid #fff',
    },
  },
  thumb: {
    width: 24,
    height: 24,
  },
  track: {
    borderRadius: 32 / 2,
    border: `1px solid #212529`,
    backgroundColor: '#212529',
    opacity: 1,
    transition: theme.transitions.create(['background-color', 'border']),
  },
  checked: {},
  focusVisible: {},
}))(({ classes, ...props }) => {
  return (
    <Switch
      focusVisibleClassName={classes.focusVisible}
      disableRipple
      classes={{
        root: classes.root,
        switchBase: classes.switchBase,
        thumb: classes.thumb,
        track: classes.track,
        checked: classes.checked,
      }}
      {...props}
    />
  );
})
Example #20
Source File: AddEditCollege.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditCollege = props => {
  const history = useHistory();
  const classes = useStyles();

  const [formState, setFormState] = useState({
    backDrop: false,
    isValid: false,
    values: {},
    adminValues: {},
    touched: {},
    errors: {},
    states: [],
    isSuccess: false,
    dynamicBar: [{ index: Math.random() }],
    dynamicBarError: [],
    isEditCollege: props["editCollege"] ? props["editCollege"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: 0,
    isStateClearFilter: false,
    showing: false,
    dataToShowForMultiSelect: [],
    addresses: genericConstants.COLLEGE_ADDRESSES,
    isCollegeAdmin:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? true
        : false
  });
  const { className, ...rest } = props;
  const [user, setUser] = useState([]);
  const [states, setStates] = useState(
    props.stateOption ? props.stateOption : []
  );
  const [zones, setZones] = useState(props.zoneOption ? props.zoneOption : []);
  const [rpcs, setRpcs] = useState(props.rpcOption ? props.rpcOption : []);
  const [districts, setDistricts] = useState(
    props.districtOption ? props.districtOption : []
  );
  const [streamsData, setStreamsData] = useState([]);
  const [streamsDataBackup, setStreamsDataBackup] = useState([]);
  const [isGetAdminData, setIsGetAdminData] = useState(false);
  const [tpoData, setTpoData] = useState([]);
  const [principalData, setPrincipalData] = useState([]);
  const [validateAddress, setValidateAddress] = useState([]);
  const inputLabel = React.useRef(null);
  const [collegeInfo, setCollegeInfo] = useState({
    college:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? auth.getUserInfo().studentInfo &&
          auth.getUserInfo().studentInfo.organization
          ? auth.getUserInfo().studentInfo.organization
          : {}
        : {},
    state:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? auth.getUserInfo().state
        : {},
    rpc:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? auth.getUserInfo().rpc
        : {},
    zone:
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? auth.getUserInfo().zone
        : {}
  });

  React.useEffect(() => {
    if (
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.MEDHAADMIN
    ) {
      setFormState(formState => ({
        ...formState,
        showing: true
      }));
    } else if (
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
    ) {
      setFormState(formState => ({
        ...formState,
        showing: false
      }));
    }
  }, []);

  /** Part for editing college */
  if (formState.isEditCollege && !formState.counter) {
    formState.backDrop = true;
    if (props["dataForEdit"]) {
      if (props["dataForEdit"]["name"]) {
        formState.values[collegeName] = props["dataForEdit"]["name"];
      }
      if (props["dataForEdit"]["college_code"]) {
        formState.values[collegeCode] = props["dataForEdit"]["college_code"];
      }
      if (props["dataForEdit"]["contact"]) {
        formState.addresses =
          props["dataForEdit"]["contact"]["addresses"].length > 0
            ? props["dataForEdit"]["contact"]["addresses"]
            : genericConstants.COLLEGE_ADDRESSES;
      }
      if (props["dataForEdit"]["contact"]) {
        formState.values[contactNumber] =
          props["dataForEdit"]["contact"]["phone"];
      }
      if (props["dataForEdit"]["contact"]) {
        formState.values[collegeEmail] =
          props["dataForEdit"]["contact"]["email"];
      }
      // if (
      //   props["dataForEdit"]["contact"] &&
      //   props["dataForEdit"]["contact"]["state"]
      // ) {
      //   formState.values["state"] = props["dataForEdit"]["contact"]["state"];
      // }
      // if (
      //   props["dataForEdit"]["contact"] &&
      //   props["dataForEdit"]["contact"]["district"]
      // ) {
      //   formState.values[district] =
      //     props["dataForEdit"]["contact"]["district"]["id"];
      // }
      if (props["dataForEdit"]["blocked"]) {
        formState.values[block] = props["dataForEdit"]["blocked"];
      }
      if (props["dataForEdit"]["zone"]) {
        formState.values["zone"] = props["dataForEdit"]["zone"]["id"];
      }
      if (props["dataForEdit"]["rpc"]) {
        formState.values["rpc"] = props["dataForEdit"]["rpc"]["id"];
      }
      if (
        props["dataForEdit"]["principal"] &&
        props["dataForEdit"]["principal"]["contact"] &&
        props["dataForEdit"]["principal"]["contact"]["user"]
      ) {
        formState.values[principal] =
          props["dataForEdit"]["principal"]["contact"]["user"];
        formState.adminValues[principal] =
          props["dataForEdit"]["principal"]["contact"]["individual"];
      }
      if (
        props["dataForEdit"]["stream_strength"] &&
        props["dataForEdit"]["stream_strength"].length
      ) {
        let dynamicBar = [];
        for (let i in props["dataForEdit"]["stream_strength"]) {
          let tempDynamicBarrValue = {};
          tempDynamicBarrValue["index"] = Math.random();
          tempDynamicBarrValue[streams] =
            props["dataForEdit"]["stream_strength"][i]["stream"]["id"];
          tempDynamicBarrValue[firstYearStrength] = props["dataForEdit"][
            "stream_strength"
          ][i]["first_year_strength"].toString();
          tempDynamicBarrValue[secondYearStrength] = props["dataForEdit"][
            "stream_strength"
          ][i]["second_year_strength"].toString();
          tempDynamicBarrValue[thirdYearStrength] = props["dataForEdit"][
            "stream_strength"
          ][i]["third_year_strength"].toString();
          dynamicBar.push(tempDynamicBarrValue);
        }
        formState.dynamicBar = dynamicBar;
      }
      formState.backDrop = false;

      formState.counter += 1;
    }
  }

  /** Here we initialize our data and bring users, states and streams*/
  useEffect(() => {
    formState.backDrop = true;
    let paramsForPageSize = {
      name_contains: "Uttar Pradesh"
    };

    serviceProviders
      .serviceProviderForGetRequest(STATES_URL, paramsForPageSize)
      .then(res => {
        formState.states = res.data.result;
        setStates(res.data.result);
      })
      .catch(error => {
        console.log("error", error);
      });

    // let params = {
    //   pageSize: -1,
    //   "state.name": "Uttar Pradesh"
    // };
    // serviceProviders
    //   .serviceProviderForGetRequest(DISTRICTS_URL, params)
    //   .then(res => {
    //     setDistricts(res.data.result);
    //   })
    //   .catch(error => {
    //     console.log("error", error);
    //   });
    serviceProviders
      .serviceProviderForGetRequest(STREAMS_URL, {
        pageSize: -1
      })
      .then(res => {
        setStreamsDataBackup(res.data.result);
      })
      .catch(error => {
        console.log("error", error);
      });
    serviceProviders
      .serviceProviderForGetRequest(STREAMS_URL, {
        pageSize: -1
      })
      .then(res => {
        let dataForEditing = res.data.result;
        if (formState.isEditCollege) {
          let tempStreamData = dataForEditing;
          let streamStrengthArray = props["dataForEdit"]["stream_strength"];
          for (let i in streamStrengthArray) {
            let id = streamStrengthArray[i]["stream"]["id"];
            for (let j in tempStreamData) {
              if (tempStreamData[j]["id"] === id) tempStreamData.splice(j, 1);
            }
          }
          setStreamsData(tempStreamData);
        } else {
          setStreamsData(dataForEditing);
        }
      })
      .catch(error => {
        console.log("error", error);
      });
    formState.backDrop = false;
  }, []);

  /** Gets data for Principals and tpos */
  useEffect(() => {
    fetchCollegeAdminData();
    return () => {};
  }, []);

  async function fetchCollegeAdminData() {
    if (auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) {
      if (formState.isEditCollege) {
        let user_url =
          COLLEGES_URL +
          "/" +
          formState.dataForEdit["id"] +
          "/" +
          strapiConstants.STRAPI_ADMIN;
        serviceProviders
          .serviceProviderForGetRequest(user_url)
          .then(res => {
            setUser(res.data.result);
            prePopulateDataForTpo(res.data.result);
          })
          .catch(error => {
            console.log("error", error);
          });
      } else {
        setUser([]);
      }
    } else if (auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN) {
      const studentId =
        auth.getUserInfo() !== null &&
        auth.getUserInfo().studentInfo &&
        auth.getUserInfo().studentInfo.organization &&
        auth.getUserInfo().studentInfo.organization.id
          ? auth.getUserInfo().studentInfo.organization.id
          : null;
      let user_url =
        COLLEGES_URL + "/" + studentId + "/" + strapiConstants.STRAPI_ADMIN;
      serviceProviders
        .serviceProviderForGetRequest(user_url)
        .then(res => {
          setUser(res.data.result);
          prePopulateDataForTpo(res.data.result);
        })
        .catch(error => {
          console.log("error", error);
        });
    }
  }

  const prePopulateDataForTpo = tpoData => {
    if (formState.isEditCollege) {
      if (
        props["dataForEdit"]["tpos"] &&
        props["dataForEdit"]["tpos"].length !== 0
      ) {
        let array = [];
        tpoData.map(tpo => {
          for (let i in props["dataForEdit"]["tpos"]) {
            if (
              props["dataForEdit"]["tpos"][i]["contact"]["individual"] ===
              tpo["id"]
            ) {
              array.push(tpo);
            }
          }
        });
        setFormState(formState => ({
          ...formState,
          dataToShowForMultiSelect: array
        }));
        let finalData = [];
        for (let i in props["dataForEdit"]["tpos"]) {
          finalData.push(
            props["dataForEdit"]["tpos"][i]["contact"]["individual"]
          );
        }
        let finalDataId = [];
        for (let i in props["dataForEdit"]["tpos"]) {
          finalDataId.push(props["dataForEdit"]["tpos"][i]["id"]);
        }
        formState.values[tpos] = finalDataId;
        formState.adminValues[tpos] = finalData;
      }
    }
  };

  /** This gets data into zones, rpcs and districts when we change the state */
  useEffect(() => {
    if (formState.addresses[0][state]) {
      fetchZoneRpcDistrictData();
    }
    return () => {};
  }, [formState.addresses[0][state]]);

  /** Common function to get zones, rpcs, districts after changing state */
  async function fetchZoneRpcDistrictData() {
    let zones_url =
      STATES_URL +
      "/" +
      formState.addresses[0][state] +
      "/" +
      strapiConstants.STRAPI_ZONES;

    await serviceProviders
      .serviceProviderForGetRequest(zones_url)
      .then(res => {
        setZones(res.data.result);
      })
      .catch(error => {
        console.log("error", error);
      });

    let rpcs_url =
      STATES_URL +
      "/" +
      formState.addresses[0][state] +
      "/" +
      strapiConstants.STRAPI_RPCS;

    await serviceProviders
      .serviceProviderForGetRequest(rpcs_url)
      .then(res => {
        if (Array.isArray(res.data)) {
          setRpcs(res.data[0].result);
        } else {
          setRpcs(res.data.result);
        }
      })
      .catch(error => {
        console.log("error", error);
      });
    let params = {
      pageSize: -1,
      "state.name": "Uttar Pradesh"
    };
    serviceProviders
      .serviceProviderForGetRequest(DISTRICTS_URL, params)
      .then(res => {
        setDistricts(res.data.result);
      })
      .catch(error => {
        console.log("error", error);
      });
    // let params = {
    //   pageSize: -1,
    //   "state.id": formState.values[state]
    // };

    // if (formState.values[state] !== undefined) {
    //   await serviceProviders
    //     .serviceProviderForGetRequest(DISTRICTS_URL, params)
    //     .then(res => {
    //       setDistricts(res.data.result);
    //     })
    //     .catch(error => {
    //       console.log("error", error);
    //     });
    // }
  }

  /** This gets Principal Email and contact number*/
  useEffect(() => {
    if (formState.adminValues[principal]) {
      getPrincipalName(formState.adminValues[principal]);
    } else {
      setIsGetAdminData(false);
      setPrincipalData([]);
    }
    return () => {};
  }, [formState.adminValues[principal]]);

  const getPrincipalName = ID => {
    let principalURL;
    principalURL =
      strapiConstants.STRAPI_DB_URL +
      strapiConstants.STRAPI_VIEW_USERS +
      "/" +
      ID;
    serviceProviders
      .serviceProviderForGetRequest(principalURL)
      .then(res => {
        setIsGetAdminData(true);
        setPrincipalData(res.data.result);
      })
      .catch(error => {
        setIsGetAdminData(false);
        console.log("error", error, error.response);
      });
  };

  /** This gets TPOs Email and contact number */
  useEffect(() => {
    if (formState.adminValues[tpos]) {
      setTpoData([]);
      getTpoName(formState.adminValues[tpos]);
    } else {
      setIsGetAdminData(false);
      setTpoData([]);
    }
    return () => {};
  }, [formState.adminValues[tpos]]);

  const getTpoName = ID => {
    let tpoURL = [];
    for (let i = 0; i < ID.length; i++) {
      tpoURL[i] =
        strapiConstants.STRAPI_DB_URL +
        strapiConstants.STRAPI_VIEW_USERS +
        "/" +
        ID[i];
    }
    serviceProviders
      .serviceProviderForAllGetRequest(tpoURL)
      .then(res => {
        let tpoarray = [];
        for (let j = 0; j < res.length; j++) {
          tpoarray.push(res[j].data.result);
        }
        setTpoData(tpoarray);
      })
      .catch(error => {
        setIsGetAdminData(false);
        console.log("error", error);
      });
  };

  /** Handle change for text fields */
  const handleChange = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [e.target.name]:
          e.target.type === "checkbox" ? e.target.checked : e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      }
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

  /** Handle change for autocomplete fields */
  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (eventName === tpos) {
      formState.dataToShowForMultiSelect = value;
    }
    if (get(CollegeFormSchema[eventName], "type") === "multi-select") {
      let finalValues = [];
      let finalIds = [];
      for (let i in value) {
        finalValues.push(value[i]["contact"]["user"]["id"]);
        finalIds.push(value[i]["id"]);
      }
      value = {
        id: finalValues,
        tpoId: finalIds
      };
    }
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value.id
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        },
        isStateClearFilter: false
      }));
      if (eventName === tpos) {
        setFormState(formState => ({
          ...formState,
          values: {
            ...formState.values,
            [eventName]: value.id
          },
          adminValues: {
            ...formState.adminValues,
            [eventName]: value.tpoId
          },
          touched: {
            ...formState.touched,
            [eventName]: true
          },
          isStateClearFilter: false
        }));
      }
      if (eventName === principal) {
        setFormState(formState => ({
          ...formState,
          values: {
            ...formState.values,
            [eventName]: value.contact.user.id
          },
          adminValues: {
            ...formState.adminValues,
            [eventName]: value.id
          },
          touched: {
            ...formState.touched,
            [eventName]: true
          },
          isStateClearFilter: false
        }));
      }
      if (eventName === state) {
        fetchZoneRpcDistrictData();
      }
      /** This is used to remove any existing errors if present in auto complete */
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    } else {
      let setStateFilterValue = false;
      /** If we click cross for state the zone and rpc should clear off! */
      if (eventName === state) {
        /** 
        This flag is used to determine that state is cleared which clears 
        off zone and rpc by setting their value to null 
        */
        setStateFilterValue = true;
        /** 
        When state is cleared then clear rpc and zone 
        */
        setRpcs([]);
        setZones([]);
        setDistricts([]);
        delete formState.values[zone];
        delete formState.values[rpc];
        delete formState.values[district];
      }
      setFormState(formState => ({
        ...formState,
        isStateClearFilter: setStateFilterValue
      }));
      /** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
      delete formState.values[eventName];
      delete formState.adminValues[eventName];
    }
  };

  /** Dynamic bar */
  const addNewRow = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,
      dynamicBar: [...formState.dynamicBar, { index: Math.random() }]
    }));
  };
  const clickOnDelete = (record, index) => {
    setFormState(formState => ({
      ...formState,
      dynamicBar: formState.dynamicBar.filter(r => r !== record)
    }));
    if (record[streams]) {
      let streamsTempArray = [];
      streamsTempArray = streamsData;
      streamsDataBackup.map(streams => {
        if (record["streams"] === streams["id"]) {
          streamsTempArray.push(streams);
        }
      });
      setStreamsData(streamsTempArray);
    }
  };

  /** Handling multi select values for dynamic bar */
  const handleChangeForDynamicGrid = (
    eventName,
    event,
    selectedValueForAutoComplete,
    dynamicGridValue,
    isAutoComplete,
    isTextBox
  ) => {
    event.persist();
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (isAutoComplete) {
      if (selectedValueForAutoComplete !== null) {
        setFormState(formState => ({
          ...formState,
          dynamicBar: formState.dynamicBar.map(r => {
            if (r["index"] === dynamicGridValue["index"]) {
              let streamsTempArray = [];
              streamsData.map(streams => {
                if (streams["id"] !== selectedValueForAutoComplete["id"]) {
                  streamsTempArray.push(streams);
                }
              });
              setStreamsData(streamsTempArray);
              r[eventName] = selectedValueForAutoComplete["id"];
              return r;
            } else {
              return r;
            }
          })
        }));
      } else {
        /** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
        setFormState(formState => ({
          ...formState,
          dynamicBar: formState.dynamicBar.map(r => {
            if (r["index"] === dynamicGridValue["index"]) {
              let streamsTempArray = [];
              streamsTempArray = streamsData;
              streamsDataBackup.map(streams => {
                if (r[eventName] === streams["id"]) {
                  streamsTempArray.push(streams);
                }
              });
              setStreamsData(streamsTempArray);
              delete r[eventName];
              return r;
            } else {
              return r;
            }
          })
        }));
      }
    }
    if (isTextBox) {
      if (
        event.target.value === "" ||
        regexForPercentage.test(event.target.value)
      ) {
        setFormState(formState => ({
          ...formState,
          dynamicBar: formState.dynamicBar.map(r => {
            if (r["index"] === dynamicGridValue["index"]) {
              r[eventName] = event.target.value;
              if (r[eventName] === "") {
                delete r[eventName];
              }
              return r;
            } else {
              return r;
            }
          })
        }));
      }
    }
    /** Clear errors if any */
    formState.dynamicBarError.map(errorValues => {
      if (errorValues["index"] === dynamicGridValue["index"]) {
        delete errorValues[eventName];
      }
    });
  };

  /** Validate DynamicGrid */
  const validateDynamicGridValues = () => {
    let validationCounter = 0;
    /** Empty the error array of dynamic bar */
    formState.dynamicBarError = [];
    formState.dynamicBar.map(value => {
      let valueToPutInDynmicBarError = {};
      valueToPutInDynmicBarError["index"] = value["index"];
      /** Validate dyanmic bar */
      if (
        value.hasOwnProperty(streams) &&
        (!value.hasOwnProperty(firstYearStrength) ||
          !value.hasOwnProperty(secondYearStrength) ||
          !value.hasOwnProperty(thirdYearStrength))
      ) {
        if (!value.hasOwnProperty(firstYearStrength))
          valueToPutInDynmicBarError[firstYearStrength] = "Required";

        if (!value.hasOwnProperty(secondYearStrength))
          valueToPutInDynmicBarError[secondYearStrength] = "Required";

        if (!value.hasOwnProperty(thirdYearStrength))
          valueToPutInDynmicBarError[thirdYearStrength] = "Required";

        validationCounter += 1;
      } else if (
        value.hasOwnProperty(firstYearStrength) &&
        value.hasOwnProperty(secondYearStrength) &&
        value.hasOwnProperty(thirdYearStrength) &&
        !value.hasOwnProperty(streams)
      ) {
        valueToPutInDynmicBarError[streams] =
          "Stream is required as Strength is present";
        validationCounter += 1;
      }
      formState.dynamicBarError.push(valueToPutInDynmicBarError);
    });
    if (validationCounter > 0) {
      return false;
    } else {
      return true;
    }
  };

  const handleSubmit = event => {
    const isValidAddress = validateAddresses();
    /** Validate DynamicGrid */
    let isDynamicBarValid;
    isDynamicBarValid = validateDynamicGridValues();
    /** Validate rest other valuesv */
    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      CollegeFormSchema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(
        formState.values,
        CollegeFormSchema
      );
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      /** This is used to find out which all required fields are not filled */
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        CollegeFormSchema
      );
      formState.errors = formUtilities.setErrors(
        formState.values,
        CollegeFormSchema
      );
    }
    /** Check if both form and dynamicBar id valid */
    if (isValid && isDynamicBarValid && isValidAddress) {
      postCollegeData();
      /** Set state to reload form */
      setFormState(formState => ({
        ...formState,
        isValid: true
      }));
    } else {
      setFormState(formState => ({
        ...formState,
        isValid: false
      }));
    }
    event.preventDefault();
  };

  const hasError = field => (formState.errors[field] ? true : false);

  const checkErrorInDynamicBar = (field, currentDynamicBarValue) => {
    let errorData = { error: false, value: "" };
    if (formState.dynamicBarError.length) {
      formState.dynamicBarError.map(barErrorValue => {
        if (barErrorValue["index"] === currentDynamicBarValue["index"]) {
          if (barErrorValue.hasOwnProperty(field)) {
            errorData.error = true;
            errorData.value = barErrorValue[field];
          }
        }
      });
    }
    return errorData;
  };

  const getDynamicBarData = () => {
    let streamStrengthArrayValues = [];
    formState.dynamicBar.map(field => {
      let streamStrengthValue = {};
      if (
        field.hasOwnProperty(streams) &&
        field.hasOwnProperty(firstYearStrength)
      ) {
        streamStrengthValue["stream"] = field[streams];
        streamStrengthValue["first_year_strength"] = parseInt(
          field[firstYearStrength]
        );
        streamStrengthValue["second_year_strength"] = parseInt(
          field[secondYearStrength]
        );
        streamStrengthValue["third_year_strength"] = parseInt(
          field[thirdYearStrength]
        );
        streamStrengthArrayValues.push(streamStrengthValue);
      }
    });
    return streamStrengthArrayValues;
  };

  const postCollegeData = async () => {
    let streamStrengthArray = [];
    const adressess = formState.addresses;
    streamStrengthArray = getDynamicBarData();
    let postData = databaseUtilities.addCollege(
      formState.values[collegeName],
      formState.values[collegeCode],
      adressess,
      formState.values[contactNumber],
      formState.values[collegeEmail].toLowerCase(),
      formState.values[block] ? formState.values[block] : false,
      formState.values[principal] ? formState.values[principal] : null,
      formState.values[state] ? formState.values[state] : null,
      formState.values[rpc] ? formState.values[rpc] : null,
      formState.values[zone] ? formState.values[zone] : null,
      formState.values[district] ? formState.values[district] : null,
      streamStrengthArray,
      formState.values[tpos] ? formState.values[tpos] : []
    );
    formState.backDrop = true;
    if (formState.isEditCollege) {
      let EDIT_COLLEGE_URL =
        strapiConstants.STRAPI_DB_URL + strapiConstants.STRAPI_CONTACT_URL;
      let EDIT_URL = strapiConstants.STRAPI_EDIT_COLLEGE;
      serviceProviders
        .serviceProviderForPutRequest(
          EDIT_COLLEGE_URL,
          formState.dataForEdit.contact["id"],
          postData,
          EDIT_URL
        )
        .then(res => {
          if (auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) {
            history.push({
              pathname: routeConstants.MANAGE_COLLEGE,
              fromeditCollege: true,
              isDataEdited: true,
              editedCollegeData: res.data,
              editResponseMessage: "",
              editedData: {}
            });
          } else if (
            auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
          ) {
            commonUtilities.updateUser();
            history.push({
              pathname: routeConstants.VIEW_COLLEGE,
              fromeditCollege: true,
              isDataEdited: true,
              editedCollegeData: res.data,
              editResponseMessage: "",
              editedData: {}
            });
          }
          formState.backDrop = false;
        })
        .catch(error => {
          console.log(error.response);
          let errorMessage;

          if (
            error.response !== undefined &&
            error.response.status !== undefined &&
            error.response.status === 400
          ) {
            if (error.response.data["message"]) {
              errorMessage = error.response.data["message"];
            }
          }
          history.push({
            pathname: routeConstants.MANAGE_COLLEGE,
            fromeditCollege: true,
            isDataEdited: false,
            editResponseMessage: errorMessage ? errorMessage : "",
            editedData: {}
          });
          formState.backDrop = false;
        });
    } else {
      serviceProviders
        .serviceProviderForPostRequest(ADD_COLLEGES_URL, postData)
        .then(res => {
          history.push({
            pathname: routeConstants.MANAGE_COLLEGE,
            fromAddCollege: true,
            isDataAdded: true,
            addedCollegeData: res.data,
            addResponseMessage: "",
            addedData: {}
          });
          formState.backDrop = false;
        })
        .catch(error => {
          console.log("errorCollege", error, error.response);
          let errorMessage;

          if (
            error.response !== undefined &&
            error.response.status !== undefined &&
            error.response.status === 400
          ) {
            if (error.response.data["message"]) {
              errorMessage = error.response.data["message"];
            }
          }
          history.push({
            pathname: routeConstants.MANAGE_COLLEGE,
            fromAddCollege: true,
            isDataAdded: false,
            addResponseMessage: errorMessage ? errorMessage : "",
            addedData: {}
          });
          formState.backDrop = false;
        });
    }
  };

  const handleStateAndDistrictChange = (type, value, idx) => {
    formState.addresses[idx][type] = value && value.id;
    if (type == "state" && formState.isCollegeAdmin) {
      formState.addresses[idx]["district"] = null;
    }

    if (type == "state" && !formState.isCollegeAdmin) {
      if (props.isCollegeAdmin) {
        formState.addresses[idx]["district"] = null;
      } else {
        formState.addresses[idx]["district"] = null;

        setRpcs([]);
        setZones([]);
        setDistricts([]);
        delete formState.values[zone];
        delete formState.values[rpc];
      }
    }
    validateAddresses();
    setFormState(formState => ({
      ...formState
    }));
  };

  const handleAddressChange = (idx, e, type) => {
    e.persist();

    const addresses = formState.addresses.map((addr, index) => {
      if (index == idx) {
        return { ...addr, [type]: e.target.value };
      } else {
        return addr;
      }
    });
    validateAddresses();
    setFormState(formState => ({
      ...formState,
      addresses
    }));
  };

  const validateAddresses = () => {
    const addresses = formState.addresses;
    let errors = [];
    let isError = false;
    addresses.forEach(addr => {
      let errorObject = {};
      if (!(addr.address_line_1 && addr.address_line_1.length > 0)) {
        isError = true;
        errorObject["address_line_1"] = {
          error: true,
          message: "Address is required"
        };
      } else {
        errorObject["address_line_1"] = {
          error: false,
          message: null
        };
      }

      if (!addr.state) {
        isError = true;
        errorObject["state"] = {
          error: true,
          message: "State is required"
        };
      } else {
        errorObject["state"] = {
          error: false,
          message: null
        };
      }

      if (!addr.district) {
        isError = true;
        errorObject["district"] = {
          error: true,
          message: "District is required"
        };
      } else {
        errorObject["district"] = {
          error: false,
          message: null
        };
      }

      if (!addr.city) {
        isError = true;
        errorObject["city"] = {
          error: true,
          message: "City is required"
        };
      } else {
        errorObject["city"] = {
          error: false,
          message: null
        };
      }

      if (!addr.pincode) {
        isError = true;
        errorObject["pincode"] = {
          error: true,
          message: "Pincode is required"
        };
      } else {
        errorObject["pincode"] = {
          error: false,
          message: null
        };
      }

      errors.push(errorObject);
    });

    setValidateAddress(errors);
    return !isError;
  };

  const clickedCancelButton = () => {
    if (auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) {
      history.push({
        pathname: routeConstants.MANAGE_COLLEGE
      });
    } else if (auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN) {
      history.push({
        pathname: routeConstants.VIEW_COLLEGE
      });
    }
  };
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          {formState.isEditCollege
            ? genericConstants.EDIT_COLLEGE_TEXT
            : genericConstants.ADD_COLLEGE_TEXT}
        </Typography>
      </Grid>
      <Grid spacing={3}>
        <Card>
          {/* <form id="form" autoComplete="off" noValidate onSubmit={handleSubmit}> */}
          <CardContent>
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <TextField
                    fullWidth
                    // helperText="Please specify the college name"
                    id={get(CollegeFormSchema[collegeName], "id")}
                    label={get(CollegeFormSchema[collegeName], "label")}
                    name={collegeName}
                    onChange={handleChange}
                    placeholder={get(
                      CollegeFormSchema[collegeName],
                      "placeholder"
                    )}
                    required
                    type={get(CollegeFormSchema[collegeName], "type")}
                    value={formState.values[collegeName] || ""}
                    error={hasError(collegeName)}
                    helperText={
                      hasError(collegeName)
                        ? formState.errors[collegeName].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <TextField
                    fullWidth
                    id={get(CollegeFormSchema[collegeCode], "id")}
                    label={get(CollegeFormSchema[collegeCode], "label")}
                    name={collegeCode}
                    onChange={handleChange}
                    placeholder={get(
                      CollegeFormSchema[collegeCode],
                      "placeholder"
                    )}
                    required
                    value={formState.values[collegeCode] || ""}
                    error={hasError(collegeCode)}
                    helperText={
                      hasError(collegeCode)
                        ? formState.errors[collegeCode].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.MarginBottom}>
                {/* <Grid item md={12} xs={12}>
                  <TextField
                    fullWidth
                    id={get(CollegeFormSchema[address], "id")}
                    label={get(CollegeFormSchema[address], "label")}
                    name={address}
                    onChange={handleChange}
                    required
                    placeholder={get(CollegeFormSchema[address], "placeholder")}
                    value={formState.values[address] || ""}
                    error={hasError(address)}
                    helperText={
                      hasError(address)
                        ? formState.errors[address].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                  />
                </Grid> */}
                {formState.addresses.map((addr, idx) => {
                  return (
                    <Grid item md={12} xs={12}>
                      <Grid item md={12} xs={12} className={classes.streamcard}>
                        <Card className={classes.streamoffer}>
                          <InputLabel
                            htmlFor="outlined-address-card"
                            fullwidth={true.toString()}
                          >
                            {addr.address_type == "Temporary"
                              ? "Local Address"
                              : "Address"}
                          </InputLabel>
                          <Grid
                            container
                            spacing={3}
                            className={classes.MarginBottom}
                          >
                            <Grid
                              item
                              md={12}
                              xs={12}
                              style={{ marginTop: "8px" }}
                            >
                              <TextField
                                id="address"
                                label="Address Line "
                                name="address"
                                value={
                                  formState.addresses[idx].address_line_1 || ""
                                }
                                variant="outlined"
                                required
                                fullWidth
                                onChange={event =>
                                  handleAddressChange(
                                    idx,
                                    event,
                                    "address_line_1"
                                  )
                                }
                                error={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["address_line_1"][
                                      "error"
                                    ]) ||
                                  false
                                }
                                helperText={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["address_line_1"][
                                      "message"
                                    ]) ||
                                  null
                                }
                              />
                            </Grid>
                          </Grid>
                          <Grid
                            container
                            spacing={3}
                            className={classes.MarginBottom}
                          >
                            <Grid item md={6} xs={12}>
                              <Autocomplete
                                id="state"
                                className={classes.root}
                                options={states}
                                getOptionLabel={option => option.name}
                                onChange={(event, value) => {
                                  handleStateAndDistrictChange(
                                    "state",
                                    value,
                                    idx
                                  );
                                }}
                                value={
                                  states[
                                    states.findIndex(function (item, i) {
                                      return (
                                        item.id ===
                                        formState.addresses[idx].state
                                      );
                                    })
                                  ] || null
                                }
                                renderInput={params => (
                                  <TextField
                                    {...params}
                                    label="State"
                                    variant="outlined"
                                    name="tester"
                                    error={
                                      (validateAddress[idx] &&
                                        validateAddress[idx]["state"][
                                          "error"
                                        ]) ||
                                      false
                                    }
                                    helperText={
                                      (validateAddress[idx] &&
                                        validateAddress[idx]["state"][
                                          "message"
                                        ]) ||
                                      null
                                    }
                                  />
                                )}
                              />
                            </Grid>
                            <Grid item md={6} xs={12}>
                              <FormControl
                                variant="outlined"
                                fullWidth
                                className={classes.formControl}
                              >
                                <InputLabel
                                  ref={inputLabel}
                                  id="districts-label"
                                >
                                  {/* Districts */}
                                </InputLabel>

                                <Autocomplete
                                  id={get(CollegeFormSchema[district], "id")}
                                  options={districts}
                                  getOptionLabel={option => option.name}
                                  onChange={(event, value) => {
                                    handleStateAndDistrictChange(
                                      "district",
                                      value,
                                      idx
                                    );
                                  }}
                                  name={district}
                                  /** This is used to set the default value to the auto complete */
                                  value={
                                    formState.isStateClearFilter
                                      ? null
                                      : districts[
                                          districts.findIndex(function (
                                            item,
                                            i
                                          ) {
                                            return (
                                              item.id ===
                                              formState.addresses[idx].district
                                            );
                                          })
                                        ] ||
                                        null /** Please give a default " " blank value */
                                  }
                                  renderInput={params => (
                                    <TextField
                                      {...params}
                                      error={
                                        (validateAddress[idx] &&
                                          validateAddress[idx]["district"][
                                            "error"
                                          ]) ||
                                        false
                                      }
                                      helperText={
                                        (validateAddress[idx] &&
                                          validateAddress[idx]["district"][
                                            "message"
                                          ]) ||
                                        null
                                      }
                                      placeholder={get(
                                        CollegeFormSchema[district],
                                        "placeholder"
                                      )}
                                      value={option => option.id}
                                      name={district}
                                      key={option => option.id}
                                      label={get(
                                        CollegeFormSchema[district],
                                        "label"
                                      )}
                                      variant="outlined"
                                    />
                                  )}
                                />
                              </FormControl>
                            </Grid>
                            <Grid item md={6} xs={12}>
                              <TextField
                                id="city"
                                label="City"
                                name="city"
                                value={formState.addresses[idx].city || ""}
                                variant="outlined"
                                required
                                fullWidth
                                onChange={event =>
                                  handleAddressChange(idx, event, "city")
                                }
                                error={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["city"]["error"]) ||
                                  false
                                }
                                helperText={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["city"]["message"]) ||
                                  null
                                }
                              />
                            </Grid>
                            <Grid item md={6} xs={12}>
                              <TextField
                                id="pincode"
                                label="Pincode"
                                name="pincode"
                                value={formState.addresses[idx].pincode || ""}
                                variant="outlined"
                                required
                                fullWidth
                                onChange={event =>
                                  handleAddressChange(idx, event, "pincode")
                                }
                                error={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["pincode"]["error"]) ||
                                  false
                                }
                                helperText={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["pincode"][
                                      "message"
                                    ]) ||
                                  null
                                }
                              />
                            </Grid>

                            <Grid item md={6} xs={12}>
                              {formState.isCollegeAdmin ? (
                                <ReadOnlyTextField
                                  id="ZoneName"
                                  label={get(CollegeFormSchema[zone], "label")}
                                  defaultValue={collegeInfo.zone.name}
                                />
                              ) : (
                                <FormControl
                                  variant="outlined"
                                  fullWidth
                                  className={classes.formControl}
                                >
                                  <InputLabel ref={inputLabel} id="zone-label">
                                    {/* Zone */}
                                  </InputLabel>

                                  <Autocomplete
                                    id={get(CollegeFormSchema[zone], "id")}
                                    options={
                                      zones ? zones : <CircularProgress />
                                    }
                                    getOptionLabel={option => option.name}
                                    onChange={(event, value) => {
                                      handleChangeAutoComplete(
                                        zone,
                                        event,
                                        value
                                      );
                                    }}
                                    /** This is used to set the default value to the auto complete */
                                    value={
                                      formState.isStateClearFilter
                                        ? null
                                        : zones[
                                            zones.findIndex(function (item, i) {
                                              return (
                                                item.id ===
                                                formState.values[zone]
                                              );
                                            })
                                          ] ||
                                          null /** Please give a default " " blank value */
                                    }
                                    name={zone}
                                    renderInput={params => (
                                      <TextField
                                        {...params}
                                        required
                                        error={hasError(zone)}
                                        helperText={
                                          hasError(zone)
                                            ? formState.errors[zone].map(
                                                error => {
                                                  return error + " ";
                                                }
                                              )
                                            : null
                                        }
                                        placeholder={get(
                                          CollegeFormSchema[zone],
                                          "placeholder"
                                        )}
                                        value={option => option.id}
                                        name={rpc}
                                        key={option => option.id}
                                        label={get(
                                          CollegeFormSchema[zone],
                                          "label"
                                        )}
                                        variant="outlined"
                                      />
                                    )}
                                  />
                                </FormControl>
                              )}
                            </Grid>
                            <Grid item md={6} xs={12}>
                              {formState.isCollegeAdmin ? (
                                <ReadOnlyTextField
                                  id={get(CollegeFormSchema[rpcs], "id")}
                                  label={get(CollegeFormSchema[rpc], "label")}
                                  defaultValue={collegeInfo.rpc.name}
                                />
                              ) : (
                                <FormControl
                                  variant="outlined"
                                  fullWidth
                                  className={classes.formControl}
                                >
                                  <InputLabel ref={inputLabel} id="rpcs-label">
                                    {/* RPCs */}
                                  </InputLabel>

                                  <Autocomplete
                                    id={get(CollegeFormSchema[rpc], "id")}
                                    options={rpcs}
                                    getOptionLabel={option => option.name}
                                    onChange={(event, value) => {
                                      handleChangeAutoComplete(
                                        rpc,
                                        event,
                                        value
                                      );
                                    }}
                                    name={rpc}
                                    /** This is used to set the default value to the auto complete */
                                    value={
                                      formState.isStateClearFilter
                                        ? null
                                        : rpcs[
                                            rpcs.findIndex(function (item, i) {
                                              return (
                                                item.id ===
                                                formState.values[rpc]
                                              );
                                            })
                                          ] ||
                                          null /** Please give a default " " blank value */
                                    }
                                    renderInput={params => (
                                      <TextField
                                        {...params}
                                        required
                                        error={hasError(rpc)}
                                        helperText={
                                          hasError(rpc)
                                            ? formState.errors[rpc].map(
                                                error => {
                                                  return error + " ";
                                                }
                                              )
                                            : null
                                        }
                                        placeholder={get(
                                          CollegeFormSchema[rpc],
                                          "placeholder"
                                        )}
                                        value={option => option.id}
                                        name={rpc}
                                        key={option => option.id}
                                        label={get(
                                          CollegeFormSchema[rpc],
                                          "label"
                                        )}
                                        variant="outlined"
                                      />
                                    )}
                                  />
                                </FormControl>
                              )}
                            </Grid>
                          </Grid>
                        </Card>
                      </Grid>
                    </Grid>
                  );
                })}
              </Grid>
            </Grid>
            <Divider className={classes.divider} />
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={12} xs={12}>
                  <TextField
                    fullWidth
                    label={get(CollegeFormSchema[collegeEmail], "label")}
                    id={get(CollegeFormSchema[collegeEmail], "id")}
                    name={collegeEmail}
                    onChange={handleChange}
                    placeholder={get(
                      CollegeFormSchema[collegeEmail],
                      "placeholder"
                    )}
                    required
                    value={formState.values[collegeEmail] || ""}
                    error={hasError(collegeEmail)}
                    helperText={
                      hasError(collegeEmail)
                        ? formState.errors[collegeEmail].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                  />
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="contact_number"
                    fullWidth
                    label={get(CollegeFormSchema[contactNumber], "label")}
                    name={contactNumber}
                    onChange={handleChange}
                    required
                    placeholder={get(
                      CollegeFormSchema[contactNumber],
                      "placeholder"
                    )}
                    value={formState.values[contactNumber] || ""}
                    error={hasError(contactNumber)}
                    helperText={
                      hasError(contactNumber)
                        ? formState.errors[contactNumber].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <div
                    style={{ display: formState.showing ? "block" : "none" }}
                  >
                    <FormGroup row>
                      <FormControlLabel
                        control={
                          <Switch
                            name={block}
                            checked={formState.values[block] || false}
                            onChange={handleChange}
                            value={formState.values[block] || false}
                            error={hasError(block).toString()}
                            helpertext={
                              hasError(block)
                                ? formState.errors[block].map(error => {
                                    return error + " ";
                                  })
                                : null
                            }
                          />
                        }
                        label={
                          formState.values[block] === true ? "Unblock" : "Block"
                        }
                      />
                    </FormGroup>
                  </div>
                </Grid>
              </Grid>
              {((auth.getUserInfo() !== null &&
                auth.getUserInfo().role !== null &&
                auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) ||
                (auth.getUserInfo() !== null &&
                  auth.getUserInfo().role !== null &&
                  auth.getUserInfo().role.name ===
                    roleConstants.COLLEGEADMIN)) &&
              formState.isEditCollege ? (
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id={get(CollegeFormSchema[tpos], "id")}
                      multiple
                      options={user}
                      getOptionLabel={option => option.contact.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(tpos, event, value);
                      }}
                      name={tpos}
                      filterSelectedOptions
                      value={formState.dataToShowForMultiSelect || null}
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError(tpos)}
                          helperText={
                            hasError(tpos)
                              ? formState.errors[tpos].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          placeholder={get(
                            CollegeFormSchema[tpos],
                            "placeholder"
                          )}
                          label={get(CollegeFormSchema[tpos], "label")}
                          variant="outlined"
                        />
                      )}
                    />
                    {/* </FormControl> */}
                  </Grid>
                </Grid>
              ) : null}
            </Grid>
            {tpoData ? (
              <Grid item xs={12} md={6} xl={3}>
                {tpoData.map(tpo => (
                  <Grid container spacing={3} className={classes.MarginBottom}>
                    <Grid item md={6} xs={12}>
                      <ReadOnlyTextField
                        id="TPO Email"
                        label={"Tpo Email"}
                        defaultValue={tpo.contact.email}
                      />
                    </Grid>
                    <Grid item md={6} xs={12}>
                      <ReadOnlyTextField
                        id="TPO Contact Number"
                        label={"TPO Contact Number"}
                        defaultValue={tpo.contact.phone}
                      />
                    </Grid>
                  </Grid>
                ))}
              </Grid>
            ) : null}
            {((auth.getUserInfo() !== null &&
              auth.getUserInfo().role !== null &&
              auth.getUserInfo().role.name === roleConstants.MEDHAADMIN) ||
              (auth.getUserInfo() !== null &&
                auth.getUserInfo().role !== null &&
                auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN)) &&
            formState.isEditCollege ? (
              <Grid item xs={12} md={6} xl={3}>
                <Grid container className={classes.formgrid}>
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id={get(CollegeFormSchema[principal], "id")}
                      options={user}
                      getOptionLabel={option => option.contact.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(principal, event, value);
                      }}
                      /** This is used to set the default value to the auto complete */
                      value={
                        user[
                          user.findIndex(function (item, i) {
                            return (
                              item.contact.user.id ===
                              formState.values[principal]
                            );
                          })
                        ] || null /** Please give a default " " blank value */
                      }
                      name={principal}
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError(principal)}
                          helperText={
                            hasError(principal)
                              ? formState.errors[principal].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          placeholder={get(
                            CollegeFormSchema[principal],
                            "placeholder"
                          )}
                          value={option => option.id}
                          name={principal}
                          key={option => option.id}
                          label={get(CollegeFormSchema[principal], "label")}
                          variant="outlined"
                        />
                      )}
                    />
                    {/* </FormControl> */}
                  </Grid>
                </Grid>
              </Grid>
            ) : null}
            {principalData && isGetAdminData ? (
              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <ReadOnlyTextField
                      id="Principal Email"
                      label={"Principal Email"}
                      defaultValue={
                        principalData.contact
                          ? principalData.contact.email
                            ? principalData.contact.email
                            : ""
                          : ""
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <ReadOnlyTextField
                      id="Principal Contact Number"
                      label={"Principal Contact Number"}
                      defaultValue={
                        principalData.contact
                          ? principalData.contact.phone
                            ? principalData.contact.phone
                            : ""
                          : ""
                      }
                    />
                  </Grid>
                </Grid>
              </Grid>
            ) : null}

            <Divider className={classes.divider} />
            <Grid item xs={12} md={10} xl={8}>
              <Grid container spacing={1} className={classes.formgrid}>
                <Grid item md={12} xs={12} className={classes.streamcard}>
                  <Card className={classes.streamoffer}>
                    <InputLabel
                      htmlFor="outlined-stream-card"
                      fullwidth={true.toString()}
                    >
                      {genericConstants.STREAMS_OFFERED_TEXT}
                    </InputLabel>

                    {formState.dynamicBar.map((val, idx) => {
                      let streamId = `stream-${idx}`,
                        firstYearStrengthId = `first-year-strength-${idx}`,
                        secondYearStrengthId = `second-year-strength-${idx}`,
                        thirdYearStrengthId = `third-year-strength-${idx}`;
                      return (
                        <Card
                          id="outlined-stream-card"
                          fullwidth={true.toString()}
                          className={classes.streamcardcontent}
                          key={idx}
                        >
                          <CardContent>
                            <Grid container spacing={1}>
                              <Grid item xs={12} md={3}>
                                <FormControl
                                  variant="outlined"
                                  fullWidth
                                  className={classes.formControl}
                                >
                                  <InputLabel
                                    ref={inputLabel}
                                    id="demo-simple-select-outlined-label"
                                  >
                                    {/* Streams */}
                                  </InputLabel>
                                  <Autocomplete
                                    id={streamId}
                                    options={streamsData}
                                    getOptionLabel={option => option.name}
                                    onChange={(event, value) => {
                                      handleChangeForDynamicGrid(
                                        streams,
                                        event,
                                        value,
                                        val,
                                        true,
                                        false
                                      );
                                    }}
                                    data-id={idx}
                                    name={streamId}
                                    value={
                                      streamsDataBackup[
                                        streamsDataBackup.findIndex(function (
                                          item,
                                          i
                                        ) {
                                          return (
                                            item.id ===
                                            formState.dynamicBar[idx][streams]
                                          );
                                        })
                                      ] || null
                                    }
                                    renderInput={params => (
                                      <TextField
                                        {...params}
                                        value={option => option.id}
                                        name={streamId}
                                        error={
                                          checkErrorInDynamicBar(streams, val)[
                                            "error"
                                          ]
                                        }
                                        helperText={
                                          checkErrorInDynamicBar(streams, val)[
                                            "error"
                                          ]
                                            ? checkErrorInDynamicBar(
                                                streams,
                                                val
                                              )["value"]
                                            : null
                                        }
                                        placeholder={get(
                                          CollegeFormSchema[streams],
                                          "placeholder"
                                        )}
                                        key={option => option.id}
                                        label={get(
                                          CollegeFormSchema[streams],
                                          "label"
                                        )}
                                        variant="outlined"
                                      />
                                    )}
                                  />
                                </FormControl>
                              </Grid>
                              {/** Need to map streams with strength */}
                              <Grid item xs>
                                <TextField
                                  label="1st Year Strength"
                                  name={firstYearStrengthId}
                                  variant="outlined"
                                  fullWidth
                                  data-id={idx}
                                  id={firstYearStrengthId}
                                  value={
                                    formState.dynamicBar[idx][
                                      firstYearStrength
                                    ] || ""
                                  }
                                  error={
                                    checkErrorInDynamicBar(
                                      firstYearStrength,
                                      val
                                    )["error"]
                                  }
                                  helperText={
                                    checkErrorInDynamicBar(
                                      firstYearStrength,
                                      val
                                    )["error"]
                                      ? checkErrorInDynamicBar(
                                          firstYearStrength,
                                          val
                                        )["value"]
                                      : null
                                  }
                                  placeholder={get(
                                    CollegeFormSchema[firstYearStrength],
                                    "placeholder"
                                  )}
                                  onChange={event => {
                                    handleChangeForDynamicGrid(
                                      firstYearStrength,
                                      event,
                                      null,
                                      val,
                                      false,
                                      true
                                    );
                                  }}
                                />
                              </Grid>
                              <Grid item xs>
                                <TextField
                                  label="2nd Year Strength"
                                  name={secondYearStrengthId}
                                  variant="outlined"
                                  fullWidth
                                  data-id={idx}
                                  id={secondYearStrengthId}
                                  value={
                                    formState.dynamicBar[idx][
                                      secondYearStrength
                                    ] || ""
                                  }
                                  error={
                                    checkErrorInDynamicBar(
                                      secondYearStrength,
                                      val
                                    )["error"]
                                  }
                                  helperText={
                                    checkErrorInDynamicBar(
                                      secondYearStrength,
                                      val
                                    )["error"]
                                      ? checkErrorInDynamicBar(
                                          secondYearStrength,
                                          val
                                        )["value"]
                                      : null
                                  }
                                  placeholder={get(
                                    CollegeFormSchema[secondYearStrength],
                                    "placeholder"
                                  )}
                                  onChange={event => {
                                    handleChangeForDynamicGrid(
                                      secondYearStrength,
                                      event,
                                      null,
                                      val,
                                      false,
                                      true
                                    );
                                  }}
                                />
                              </Grid>
                              <Grid item xs>
                                <TextField
                                  label="3rd Year Strength"
                                  name={thirdYearStrengthId}
                                  variant="outlined"
                                  fullWidth
                                  data-id={idx}
                                  id={thirdYearStrengthId}
                                  value={
                                    formState.dynamicBar[idx][
                                      thirdYearStrength
                                    ] || ""
                                  }
                                  error={
                                    checkErrorInDynamicBar(
                                      thirdYearStrength,
                                      val
                                    )["error"]
                                  }
                                  helperText={
                                    checkErrorInDynamicBar(
                                      thirdYearStrength,
                                      val
                                    )["error"]
                                      ? checkErrorInDynamicBar(
                                          thirdYearStrength,
                                          val
                                        )["value"]
                                      : null
                                  }
                                  placeholder={get(
                                    CollegeFormSchema[thirdYearStrength],
                                    "placeholder"
                                  )}
                                  onChange={event => {
                                    handleChangeForDynamicGrid(
                                      thirdYearStrength,
                                      event,
                                      null,
                                      val,
                                      false,
                                      true
                                    );
                                  }}
                                />
                              </Grid>
                              <Grid item xs={1}>
                                {idx > 0 ? (
                                  <DeleteForeverOutlinedIcon
                                    onClick={e => clickOnDelete(val, idx)}
                                    style={{ color: "red", fontSize: "24px" }}
                                  />
                                ) : (
                                  ""
                                )}
                              </Grid>
                            </Grid>
                          </CardContent>
                        </Card>
                      );
                    })}
                    <div className={classes.btnspaceadd}>
                      <Grid item xs={12} md={3} lg={2} xl={2}>
                        <YellowButton
                          disabled={streamsData.length ? false : true}
                          color="primary"
                          variant="contained"
                          className={classes.add_more_btn}
                          onClick={addNewRow}
                        >
                          {genericConstants.ADD_MORE_TEXT}
                        </YellowButton>
                      </Grid>
                    </div>
                  </Card>
                </Grid>
              </Grid>
            </Grid>
          </CardContent>
          <Grid item xs={12} className={classes.CardActionGrid}>
            <CardActions className={classes.btnspace}>
              <Grid item xs={12}>
                <Grid item xs={12} md={6} xl={3}>
                  <Grid container spacing={3}>
                    <Grid item md={2} xs={12}>
                      <YellowButton
                        id="submit"
                        type="submit"
                        color="primary"
                        variant="contained"
                        onClick={handleSubmit}
                        className={classes.submitbtn}
                      >
                        {genericConstants.SAVE_BUTTON_TEXT}
                      </YellowButton>
                    </Grid>
                    <Grid item md={2} xs={12}>
                      <GrayButton
                        color="primary"
                        variant="contained"
                        onClick={clickedCancelButton}
                        className={classes.resetbtn}
                      >
                        {genericConstants.CANCEL_BUTTON_TEXT}
                      </GrayButton>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </CardActions>
          </Grid>
          {/* </form> */}
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={formState.backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #21
Source File: NavBar.js    From to-view-list with MIT License 4 votes vote down vote up
NavBar = () => {
  const [anchorEl, setAnchorEl] = useState(null);
  const [{ user }, authDispatch] = useAuthContext();
  const [{ darkMode }, entryDispatch] = useEntryContext();
  const location = useLocation();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('xs'));
  const classes = useNavStyles();

  const open = Boolean(anchorEl);

  const handleMenu = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleLogout = () => {
    authDispatch(logoutUser());
    storageService.logoutUser();
    if (isMobile) {
      handleClose();
    }
  };

  const handleDarkMode = () => {
    entryDispatch(toggleDarkMode());
    storageService.saveDarkMode(!darkMode);
    if (isMobile) {
      handleClose();
    }
  };

  const loggedUser = storageService.loadUser() || user;

  const mobileMenu = () => {
    return user ? (
      <div>
        <MenuItem onClick={() => handleClose()}>
          Hi, {user && user.displayName}
        </MenuItem>
        <MenuItem onClick={handleLogout}>Logout</MenuItem>{' '}
      </div>
    ) : (
      <div>
        <MenuItem
          component={RouterLink}
          to="/register"
          onClick={() => handleClose()}
        >
          Register
        </MenuItem>
        <MenuItem
          component={RouterLink}
          to="/login"
          onClick={() => handleClose()}
        >
          Login
        </MenuItem>{' '}
      </div>
    );
  };

  const desktopMenu = () => {
    return user ? (
      <>
        <Typography variant="body1" className={classes.user}>
          Hi, {user && user.displayName}
        </Typography>
        <Button
          color="inherit"
          startIcon={<PowerSettingsNewIcon />}
          onClick={handleLogout}
          className={classes.navButtons}
        >
          Logout
        </Button>{' '}
      </>
    ) : (
      <>
        <Button
          component={RouterLink}
          to="/register"
          color="inherit"
          className={classes.navButtons}
        >
          Register
        </Button>
        <Button
          component={RouterLink}
          to="/login"
          color="inherit"
          className={classes.navButtons}
        >
          Login
        </Button>
      </>
    );
  };

  const darkModeSwitch = () => {
    if (isMobile) {
      return <Switch checked={darkMode} onChange={handleDarkMode} />;
    }

    return (
      <Switch
        checked={darkMode}
        onChange={handleDarkMode}
        icon={<Brightness7Icon style={{ color: ' #f9a723' }} />}
        checkedIcon={<Brightness4Icon style={{ color: '#6a0dad' }} />}
      />
    );
  };

  return (
    <Container disableGutters className={classes.navContainer}>
      <AppBar color="primary" elevation={1} position="static">
        <Toolbar variant="dense" disableGutters={isMobile}>
          <div className={classes.topLeftButton}>
            {location.pathname === '/' || !loggedUser ? (
              <div className={classes.logoWrapper}>
                <Typography variant="h6" className={classes.logo}>
                  <ListAltRoundedIcon className={classes.logoIcon} />
                  ToViewList
                </Typography>
                <Typography variant="caption" className={classes.madeBy}>
                  Made with <FavoriteIcon style={{ fontSize: 11 }} /> by{' '}
                  <Link
                    href={'https://github.com/amand33p'}
                    color="inherit"
                    target="_blank"
                    rel="noopener"
                  >
                    amand33p
                  </Link>
                </Typography>
              </div>
            ) : (
              <Button
                component={RouterLink}
                to="/"
                color="inherit"
                startIcon={<ArrowBackIcon />}
              >
                Back
              </Button>
            )}
          </div>
          {isMobile ? (
            <>
              <IconButton onClick={handleMenu} color="inherit">
                <MoreVertIcon />
              </IconButton>
              <Menu
                keepMounted
                anchorEl={anchorEl}
                anchorOrigin={{
                  vertical: 'top',
                  horizontal: 'right',
                }}
                transformOrigin={{
                  vertical: 'top',
                  horizontal: 'right',
                }}
                open={open}
                onClose={handleClose}
              >
                {mobileMenu()}
                <MenuItem>
                  Dark mode:
                  {darkModeSwitch()}
                </MenuItem>
              </Menu>
            </>
          ) : (
            <>
              {desktopMenu()}
              {darkModeSwitch()}
            </>
          )}
        </Toolbar>
      </AppBar>
    </Container>
  );
}
Example #22
Source File: Posts.js    From Athavani with MIT License 4 votes vote down vote up
Posts = ({setCurrentId, setOpenCreatePost}) =>{

    const history = useHistory();
    const [creatorID, setCreatorID] = useState("");
    const [isFavoritePosts, setIsFavoritePosts] = useState(false);
    //const [searchTagPosts, setSearchTagPosts] = useState([]);
    //const [searchTag, setSearchTag] = useState("");
    const searchTagPosts = [];
    const searchTag = "";
    
    useEffect(()=>{
        (async () => {
            try {
                const {data} = await api.verify({token : localStorage.getItem('token')});
                setCreatorID(data.id);
            } catch(error) {
                localStorage.removeItem('token');
                history.push('/signin');
            }
        })();
    }, [isFavoritePosts]);

    const posts = useSelector((state) => state.posts)
    const classes = useStyles();

    const [anchorEl, setAnchorEl] = useState(null);

    const handleClick = (event) => {
        setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
        setAnchorEl(null);
    };

    const [isReversed, setIsReversed] = useState(false);

    function sort(reverse) {
        if((reverse && !isReversed) || (!reverse && isReversed)) {
                posts.reverse();
                setIsReversed(current => !current);
        }
    }
    
    // const searchForTag = (e) => {
    //     setSearchTagPosts([])

    //     let a = posts.filter(
    //             (p, i) => p.tags.includes(e.target.value)
    //         )
    //     setSearchTagPosts(a);
    // }
   
    return(
        !posts.length ? <CircularProgress/> : (
            <>
                <div style={{
                    display: "flex",
                    justifyContent: "space-between",
                    margin: "5px"
                }}>
                    <Typography component="div">
                        <Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick} className={classes.filterButtons} style={{ background: "#ff7300" }}>
                            Sort
                        </Button>
                        <Menu
                            id="simple-menu"
                            anchorEl={anchorEl}
                            keepMounted
                            open={Boolean(anchorEl)}
                            onClose={handleClose}
                        >
                            <MenuItem onClick={() => {
                                handleClose();
                                sort(false);
                                }}>By Newest</MenuItem>
                            <MenuItem onClick={() => {
                                handleClose();
                                sort(true);
                                }}>By Oldest</MenuItem>
                        </Menu>
                    </Typography>
                    <Typography component="div">
                        <Grid component="label" container alignItems="center" spacing={1}>
                        <Grid item style={{
                            color: "black",
                            fontSize: "1.2em",
                            fontWeight: "500"
                        }}>All Posts</Grid>
                        <Grid item>
                            <FormControlLabel
                                control={
                                    <Switch 
                                    checked={isFavoritePosts}
                                    onChange={(e) => setIsFavoritePosts(e.target.checked)}
                                    color="secondary"
                                    name="checkedB"
                                    inputProps={{ 'aria-label': 'primary checkbox' }}
                                />}
                            />
                        </Grid>
                        <Grid item style={{
                            color: "black",
                            fontSize: "1.2em",
                            fontWeight: "500"
                        }}>My Favorite Posts</Grid>
                        </Grid>
                    </Typography>
                </div>
                <Grid className={classes.mainContainer} container alignItems="stretch" spacing={3}>
                    { !searchTag ? (
                        posts.slice(0).reverse().map((post)=> {
                            if(isFavoritePosts && !post.favorites.includes(creatorID)) {
                                return (<></>)
                            } else {
                                console.log(searchTagPosts);
                                return (<Grid key={post._id} item xs={12} sm={12} lg={6}>
                                    <Post post={post} setCurrentId={setCurrentId} setOpenCreatePost={setOpenCreatePost}/>
                                </Grid>
                                )
                            }})
                    ) : (
                        searchTagPosts.slice(0).reverse().map((post)=> {
                            if(isFavoritePosts && !post.favorites.includes(creatorID)) {
                                return (<></>)
                            } else {
                                return (<Grid key={post._id} item xs={12} sm={12} lg={6}>
                                    <Post post={post} setCurrentId={setCurrentId} setOpenCreatePost={setOpenCreatePost}/>
                                </Grid>)
                            }})
                    )}
                </Grid>
            </>
        )
    )
}
Example #23
Source File: index.js    From yi-note with GNU General Public License v3.0 4 votes vote down vote up
Video = () => {
  const { t } = useTranslation('options');
  const {
    data: {
      [KEY_VIDEO_SEEK_SECONDS]: seekSecond = 0,
      [KEY_APPLY_SEEK_SEC_ON_URL]: applySeekSecondsOnUrl = false,
      [KEY_RELOAD_TAB]: reloadTab = false,
      [KEY_RELOAD_TAB_ALLOWED_DOMAINS]: reloadTabDomains = [],
      [KEY_PAUSE_VIDEO_WHEN_EDITING]: pauseWhenEditing = false
    }
  } = useStoreState(state => state.settings);
  const { setSetting } = useStoreActions(actions => actions.settings);
  const [domain, setDomain] = useState('');

  const handleSecondChange = e => {
    const { value } = e.target;
    setSetting({ [KEY_VIDEO_SEEK_SECONDS]: value });
  };

  const handleApplySeekSecondsOnUrlChange = e => {
    const { checked } = e.target;
    setSetting({ [KEY_APPLY_SEEK_SEC_ON_URL]: checked });
  };

  const handleReloadTabChange = e => {
    const { checked } = e.target;
    setSetting({ [KEY_RELOAD_TAB]: checked });
  };

  const handleAddDomain = e => {
    e.preventDefault();
    setSetting({
      [KEY_RELOAD_TAB_ALLOWED_DOMAINS]: [
        ...reloadTabDomains.filter(d => d !== domain),
        domain
      ]
    });
    setDomain('');
  };

  const handleDomainChange = e => {
    const { value } = e.target;
    setDomain(value);
  };

  const handleDeleteDomain = domain => {
    const domains = reloadTabDomains.filter(d => d !== domain);
    setSetting({ [KEY_RELOAD_TAB_ALLOWED_DOMAINS]: domains });
  };

  const handlePauseWhenEditingChange = e => {
    const { checked } = e.target;
    setSetting({ [KEY_PAUSE_VIDEO_WHEN_EDITING]: checked });
  };

  return (
    <Grid container direction="column" spacing={3}>
      <Grid item container spacing={1} direction="column">
        <Grid item>
          <Typography variant="h6">{t('settings.video.title')}</Typography>
        </Grid>
        <Grid item>
          <Divider />
        </Grid>
        <Grid item>
          <Typography variant="body1" color="textSecondary">
            {t('settings.video.description')}
          </Typography>
        </Grid>
      </Grid>
      <Grid item container spacing={4} alignItems="center">
        <Grid item>
          <Typography variant="subtitle1">
            {t('settings.seek.label')}
          </Typography>
        </Grid>
        <Grid item>
          <Select value={seekSecond} onChange={handleSecondChange}>
            <MenuItem value={0}>0</MenuItem>
            <MenuItem value={5}>5</MenuItem>
            <MenuItem value={10}>10</MenuItem>
            <MenuItem value={15}>15</MenuItem>
          </Select>
        </Grid>
      </Grid>
      <Grid item container spacing={4} alignItems="center">
        <Grid item>
          <Typography variant="subtitle1">
            {t('settings.seek.generated.url.label')}
          </Typography>
        </Grid>
        <Grid item>
          <Switch
            checked={applySeekSecondsOnUrl}
            onChange={handleApplySeekSecondsOnUrlChange}
            name="applySeekSecondsOnUrl"
          />
        </Grid>
      </Grid>
      <Grid item container spacing={4} alignItems="center">
        <Grid item>
          <Typography variant="subtitle1">
            {t('settings.pause.when.editing.label')}
          </Typography>
        </Grid>
        <Grid item>
          <Switch
            checked={pauseWhenEditing}
            onChange={handlePauseWhenEditingChange}
            name="pauseWhenEditing"
          />
        </Grid>
      </Grid>
      <Grid item container direction="column" spacing={1}>
        <Grid item container direction="row" alignItems="center">
          <Grid item>
            <Typography variant="subtitle1">
              {t('settings.reload.tab.label')}
            </Typography>
          </Grid>
          <Grid item>
            <Switch
              checked={reloadTab}
              onChange={handleReloadTabChange}
              name="reloadTab"
            />
          </Grid>
        </Grid>
        {reloadTab &&
          reloadTabDomains.map(domain => (
            <Grid
              key={domain}
              item
              container
              direction="row"
              alignItems="center"
            >
              <Grid item>
                <Typography>{domain}</Typography>
              </Grid>
              <Grid item>
                <IconButton
                  size="small"
                  onClick={handleDeleteDomain.bind(null, domain)}
                >
                  <CloseIcon />
                </IconButton>
              </Grid>
            </Grid>
          ))}
        {reloadTab && (
          <Grid item>
            <form onSubmit={handleAddDomain}>
              <TextField
                label="Allowed domain"
                required
                value={domain}
                onChange={handleDomainChange}
              />
            </form>
          </Grid>
        )}
      </Grid>
    </Grid>
  );
}
Example #24
Source File: Settings.js    From qasong with ISC License 4 votes vote down vote up
export default function TransitionsModal({
  showSettings,
  setShowSettings,
  darkMode,
  setDarkMode,
  playbackRate,
  setPlaybackRate,
}) {
  const classes = useStyles();

  const handleClose = () => {
    setShowSettings(false);
  };

  function handleDarkmodeButtonClick() {
    setDarkMode(!darkMode);
  }

  function handleChangePlaybackRate(e) {
    setPlaybackRate(e.target.value);
  }

  // function handleChangeLanguage(e){
  //   console.log(e)
  //   setSelectedLanguage(e.target.value)
  // }

  return (
    <Dialog
      className={classes.modal}
      open={showSettings}
      onClose={handleClose}
      PaperProps={{
        classes: {
          root: classes.paper,
        },
      }}
    >
      <Fade in={showSettings}>
        <>
          <Typography gutterBottom variant="h4" align="center">
            Settings
          </Typography>

          <Grid>
            <Grid>
              {/* dark mode */}
              <FormControlLabel
                control={
                  <Switch onChange={handleDarkmodeButtonClick} checked={darkMode} />
                }
                label="Dark Mode"
                labelPlacement="start"
              />
            </Grid>

            <Grid>
              <FormControlLabel
                label="Playback Speed"
                labelPlacement="start"
                control={
                  <Select
                    className={classes.select}
                    defaultValue={1}
                    value={playbackRate}
                    onChange={handleChangePlaybackRate}
                  >
                    <MenuItem value={0.25}>0.25</MenuItem>
                    <MenuItem value={0.5}>0.50</MenuItem>
                    <MenuItem value={0.75}>0.75</MenuItem>
                    <MenuItem value={1}>normal</MenuItem>
                    <MenuItem value={1.25}>1.25</MenuItem>
                    <MenuItem value={1.5}>1.5</MenuItem>
                    <MenuItem value={1.75}>1.75</MenuItem>
                    <MenuItem value={2}>2</MenuItem>
                  </Select>
                }
              />
            </Grid>

            <Grid>
              {/* <FormControlLabel
                  label="Language"
                  labelPlacement="start"
                  control={
                    <Select
                      className={classes.select}
                      defaultValue="en"
                      value={selectedLanguage}
                      onChange={handleChangeLanguage}
                    >
                      <MenuItem value="en">english</MenuItem>
                      <MenuItem value="ro">romanian</MenuItem>
                    </Select>
                  }
                /> */}
            </Grid>
          </Grid>
        </>
      </Fade>
    </Dialog>
  );
}
Example #25
Source File: AddGroupMembers.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function AddGroupMembers
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function AddGroupMembers(props) {
  const refs = {
    add_group_members_el: React.useRef(null),
    drag_drop_el: React.useRef(null),
  };
  const classes = useStyles();
  const common_classes = useCommonStyles();

  const [state, setState] = React.useState({
    loading: true,
    error: null,
    csv: null,
    upload_dialog: false,
    bulk_add_checked: false,
  });

  const handleSetState = obj => {
    if (obj) {
      Promise.resolve(obj).then(obj => {
        setState({ ...state, ...obj });
      });
    }
  };

  const { upload_dialog, bulk_add_checked, csv } = state;
  const { t } = props;
  vars.csv_not_added = !csv;
  if (!props.auth.token) {
    return <ErrorPage error={t('addGroupMembers.errors.notLoggedIn')} />;
  } else if (props.auth.members_count === null) {
    return <ErrorPage error={t('addGroupMembers.errors.unauthorized')} />;
  } else {
    return (
      <Box className={classes.root}>
        <Container className={classes.containerStyle}>
          <Card className={classes.cardStyle}>
            <CardActionArea>
              <CardContent>
                <form
                  className="project-create-form"
                  name="create_project"
                  noValidate="noValidate"
                  onSubmit={e => handleSubmit(e, state, handleSetState, props)}
                >
                  <Typography
                    className={classes.titleStyle}
                    gutterBottom
                    variant="h5"
                    component="h2"
                    color="textPrimary"
                  >
                    {t('addGroupMembers.welcomeMsg.primary')}
                  </Typography>
                  <Typography
                    variant="body2"
                    color="textSecondary"
                    component="p"
                    className={classes.descStyle}
                  >
                    {t('addGroupMembers.welcomeMsg.secondary')}
                  </Typography>

                  <Grid container spacing={3}>
                    <Grid item xs={12}>
                      <Box
                        component="p"
                        className={
                          props.status &&
                          props.status['non_field_errors'] &&
                          classes.errorBox
                        }
                      >
                        {props.status && props.status['non_field_errors'] && (
                          <Box component="span" className={classes.error}>
                            {props.status['non_field_errors']}
                          </Box>
                        )}
                      </Box>
                    </Grid>

                    <Grid item xs={12} className={common_classes.marginTop1em}>
                      <FormControl
                        variant="outlined"
                        size="small"
                        fullWidth
                        margin="small"
                        error={
                          (props.status && props.status['group_members']) ||
                          (props.touched['group_members'] &&
                            props.errors['group_members'])
                        }
                      >
                        <label htmlFor="add_group_members">
                          <Typography
                            color="textSecondary"
                            className={clsx(
                              classes.customLabelStyle,
                              common_classes.marginBottom1em,
                            )}
                          >
                            {t('addGroupMembers.inputs.groupMembers.label')}
                          </Typography>
                        </label>

                        <Grid container spacing={1} alignItems="flex-end">
                          {!bulk_add_checked ? (
                            <>
                              <Grid item xs={12} sm={8}>
                                <Box ref={refs.add_group_members_el}>
                                  {buildGroupMembersNodes({
                                    props,
                                    refs,
                                    classes,
                                    common_classes,
                                  })}
                                </Box>
                              </Grid>
                              <Grid item xs={12} sm={4}>
                                <CustomButton
                                  variant="outlined"
                                  size="large"
                                  onClick={e => addGroupMembersNode(e, props)}
                                  secondaryButtonStyle
                                  customButtonStyle
                                  fullWidth
                                >
                                  <AddIcon />{' '}
                                  {t(
                                    'addGroupMembers.inputs.groupMembers.addMore',
                                  )}
                                </CustomButton>
                              </Grid>
                              <FormHelperText
                                error
                                className={classes.fieldHelperTextStyle}
                              >
                                {(props.status &&
                                  props.status['group_members']) ||
                                  (props.touched['group_members'] &&
                                    props.errors['group_members'] &&
                                    t(
                                      `addGroupMembers.inputs.groupMembers.errors.${props.errors['group_members']}`,
                                    ))}
                              </FormHelperText>
                            </>
                          ) : (
                            <label
                              htmlFor="addcsv"
                              className={classes.addCSVStyles}
                            >
                              <Box
                                className={classes.CSVBoxStyles}
                                ref={refs.drag_drop_el}
                                onDragLeave={e => {
                                  refs.drag_drop_el.current.style.border =
                                    '1px dashed rgb(196, 194, 194)';
                                }}
                                onDragOver={e => {
                                  e.preventDefault();
                                  refs.drag_drop_el.current.style.border =
                                    '1px solid #878dcd';
                                }}
                                onDrop={e =>
                                  handleSetState(handleAddCSV(e, refs))
                                }
                              >
                                <img
                                  src={csvLogo}
                                  alt={
                                    csv
                                      ? csv.name
                                      : t(
                                          'addGroupMembers.inputs.groupMembers.addCSV',
                                        )
                                  }
                                />
                                <br />
                                {csv
                                  ? csv.name
                                  : t(
                                      'addGroupMembers.inputs.groupMembers.addCSV',
                                    )}
                                <FormHelperText
                                  error
                                  className={classes.fieldHelperTextStyle}
                                >
                                  {(props.status &&
                                    props.status['group_members']) ||
                                    (props.touched['group_members'] &&
                                      props.errors['group_members'] &&
                                      t(
                                        `addGroupMembers.inputs.groupMembers.errors.${props.errors['group_members']}`,
                                      ))}
                                </FormHelperText>
                                <input
                                  type="file"
                                  accept=".csv"
                                  style={{ display: 'none' }}
                                  id="addcsv"
                                  onChange={e =>
                                    handleSetState({
                                      csv: e.target.files[0],
                                    })
                                  }
                                />
                              </Box>
                            </label>
                          )}
                        </Grid>
                      </FormControl>
                    </Grid>
                    <Grid item xs={12} sm={8}>
                      <FormControlLabel
                        className={common_classes.floatLeft}
                        control={
                          <Switch
                            className={classes.bulkAddStyles}
                            checked={bulk_add_checked}
                            onChange={e =>
                              handleSetState(
                                handleBulkAddCheck(bulk_add_checked),
                              )
                            }
                          />
                        }
                        label={
                          <Typography
                            color="textSecondary"
                            className={classes.customLabelStyle}
                          >
                            {t('addGroupMembers.inputs.groupMembers.bulkAdd')}
                          </Typography>
                        }
                      />
                    </Grid>
                    <Grid item xs={12} sm={4}>
                      <CustomButton
                        variant="contained"
                        size="large"
                        type="submit"
                        primaryButtonStyle
                        customButtonStyle
                        fullWidth
                        className={common_classes.floatRight}
                      >
                        {t('addGroupMembers.inputs.submit')}
                      </CustomButton>
                    </Grid>
                  </Grid>
                </form>
                <Dialog
                  PaperProps={{
                    style: {
                      backgroundColor: 'transparent',
                      boxShadow: 'none',
                      overflow: 'hidden',
                    },
                  }}
                  open={upload_dialog}
                  aria-label={t('addGroupMembers.ariaLabels.submitting')}
                >
                  <Box position="relative" display="inline-flex">
                    <CircularProgress
                      className={classes.uploadProgressStyle}
                      size={70}
                      thickness={6}
                    />
                  </Box>
                </Dialog>
              </CardContent>
            </CardActionArea>
          </Card>
        </Container>
      </Box>
    );
  }
}
Example #26
Source File: Regions.js    From treetracker-admin-client with GNU Affero General Public License v3.0 4 votes vote down vote up
EditModal = ({
  openEdit,
  setOpenEdit,
  isUpload,
  selectedItem,
  styles,
  upload,
  updateRegion,
  updateCollection,
  showSnackbar,
}) => {
  const [errors, setErrors] = useState({});
  const [id, setId] = useState(undefined);
  const [ownerId, setOwnerId] = useState(undefined);
  const [name, setName] = useState(undefined);
  const [regionNameProperty, setRegionNameProperty] = useState(undefined);
  const [show, setShow] = useState(true);
  const [calc, setCalc] = useState(true);
  const [geojson, setGeoJson] = useState(undefined);
  const [shape, setShape] = useState(undefined);
  const [isCollection, setIsCollection] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const [shapeProperties, setShapeProperties] = useState([]);
  const { orgList, userHasOrg } = useContext(AppContext);

  const reset = () => {
    setShape(undefined);
    setGeoJson(undefined);
    setRegionNameProperty(undefined);
    setId(undefined);
    setName(undefined);
    setRegionNameProperty(undefined);
    setShow(true);
    setCalc(true);
    setIsCollection(false);
    setOwnerId(undefined);
    setErrors({});
  };

  useEffect(() => {
    reset();
    if (selectedItem) {
      setId(selectedItem.id);
      setOwnerId(selectedItem.owner_id);
      setName(selectedItem.name);
      if (selectedItem.isCollection) {
        setIsCollection(true);
      } else {
        setShow(selectedItem.show_on_org_map);
        setCalc(selectedItem.calculate_statistics);
      }
    } else {
      setOwnerId(getOrganizationUUID());
    }
  }, [selectedItem]);

  useEffect(() => {
    if (shape?.type?.endsWith('Collection')) {
      setIsCollection(true);
      setShapeProperties(
        (shape?.features || []).reduce((props, feature) => {
          return [
            ...new Set([...props, ...Object.keys(feature.properties || {})]),
          ];
        }, [])
      );
    } else {
      setShapeProperties(shape?.properties || []);
    }
  }, [shape]);

  useEffect(() => {
    // Auto-set to "name" if present
    const nameProp = shapeProperties?.find(
      (prop) => prop.toLowerCase() === 'name'
    );
    if (nameProp) {
      setRegionNameProperty(nameProp);
    }
  }, [shapeProperties]);

  const onOwnerChange = (e) => {
    setOwnerId(e.target.value);
    setErrors((prev) => ({
      ...prev,
      owner: undefined,
    }));
  };

  const onNameChange = (e) => {
    setName(e.target.value);
    setErrors((prev) => ({
      ...prev,
      name: undefined,
    }));
  };

  const onRegionNamePropertyChange = (e) => {
    setRegionNameProperty(e.target.value);
    setErrors((prev) => ({
      ...prev,
      name: undefined,
    }));
  };

  const onShowChange = (e) => {
    setShow(e.target.checked);
  };

  const onCalcChange = (e) => {
    setCalc(e.target.checked);
  };

  const onFileChange = (e) => {
    setErrors((prev) => ({
      ...prev,
      shape: undefined,
    }));
    const fileread = new FileReader();
    try {
      fileread.onload = function (e) {
        const content = e.target.result;
        const json = JSON.parse(content);
        setShape(json);
      };
    } catch (error) {
      setErrors((prev) => ({
        ...prev,
        shape: `Failed to process shape file: ${error}`,
      }));
    }
    fileread.readAsText(e.target.files[0]);
    setGeoJson(e.target.value);
  };

  const handleEditDetailClose = () => {
    setOpenEdit(false);
  };

  const handleSave = async () => {
    let hasError = false;
    if (isUpload) {
      if (!shape) {
        hasError = true;
        setErrors((prev) => {
          return { ...prev, shape: 'Please select a shape file.' };
        });
      } else if (!regionNameProperty) {
        hasError = true;
        setErrors((prev) => {
          return { ...prev, name: 'Please select a region name property.' };
        });
      }
    }

    if ((!isUpload || isCollection) && !name) {
      hasError = true;
      setErrors((prev) => {
        return {
          ...prev,
          name: `Please enter a name for the ${
            isCollection ? 'collection' : 'region'
          }.`,
        };
      });
    }

    if (!hasError) {
      setSaveInProgress(true);
      let res;
      try {
        if (isUpload) {
          res = await upload({
            id,
            owner_id: ownerId,
            collection_name: isCollection ? name : undefined,
            region_name_property: regionNameProperty,
            shape,
            show_on_org_map: show,
            calculate_statistics: calc,
          });
        } else {
          if (isCollection) {
            res = await updateCollection({
              id,
              owner_id: ownerId,
              name,
            });
          } else {
            res = await updateRegion({
              id,
              owner_id: ownerId,
              name,
              show_on_org_map: show,
              calculate_statistics: calc,
            });
          }
        }

        if (res?.error) {
          throw res.message;
        } else {
          showSnackbar(
            `${isCollection ? 'Collection' : res?.region?.name} ${
              isUpload ? 'uploaded' : 'updated'
            }`
          );
          setOpenEdit(false);
        }
      } catch (error) {
        // TO DO - report the error details
        alert(`Upload failed: ${error}`);
      }
      setSaveInProgress(false);
    }
  };

  return (
    <Dialog open={openEdit} aria-labelledby="form-dialog-title">
      <DialogTitle id="form-dialog-title">
        {isUpload
          ? 'Upload New Region or Collection'
          : `Edit ${isCollection ? 'Collection' : 'Region'}`}
      </DialogTitle>
      <DialogContent>
        {isUpload && (
          <>
            <Grid container>
              <Grid item className={styles.input}>
                <Input
                  type="file"
                  value={geojson || ''}
                  onChange={onFileChange}
                  inputProps={{
                    accept: '.json,.geojson',
                  }}
                  error={errors.shape ? true : false}
                />
              </Grid>
            </Grid>
            {shape && (
              <Grid container>
                <Grid item className={styles.input}>
                  <Typography>
                    {isCollection ? 'Collection' : 'Region'}
                  </Typography>
                </Grid>
              </Grid>
            )}
          </>
        )}
        <Grid container>
          {!userHasOrg && (
            <Grid item className={styles.owner}>
              <TextField
                error={errors.owner ? true : false}
                helperText={errors.owner}
                select
                className={styles.input}
                id="owner"
                label="Owner"
                value={ownerId || ''}
                onChange={onOwnerChange}
                fullWidth
              >
                <MenuItem key={'null'} value={null}>
                  No owner
                </MenuItem>
                {orgList.length &&
                  orgList.map((org) => (
                    <MenuItem
                      key={org.stakeholder_uuid}
                      value={org.stakeholder_uuid}
                    >
                      {org.name}
                    </MenuItem>
                  ))}
              </TextField>
            </Grid>
          )}

          <Grid item>
            {(!isUpload || isCollection) && (
              <TextField
                error={errors.name ? true : false}
                helperText={errors.name}
                id="name"
                label={`${isCollection ? 'Collection' : 'Region'} Name`}
                type="text"
                variant="outlined"
                fullWidth
                value={name || ''}
                className={styles.input}
                onChange={onNameChange}
              />
            )}
            {isUpload && (
              <TextField
                select
                error={errors.name ? true : false}
                helperText={errors.name}
                id="prop"
                label="Region Name Property"
                type="text"
                variant="outlined"
                fullWidth
                value={regionNameProperty || ''}
                className={styles.input}
                onChange={onRegionNamePropertyChange}
              >
                {shapeProperties.length ? (
                  shapeProperties.map((prop) => (
                    <MenuItem key={prop} value={prop}>
                      {prop}
                    </MenuItem>
                  ))
                ) : (
                  <MenuItem key={'null'} value={null}>
                    No properties found
                  </MenuItem>
                )}
              </TextField>
            )}
          </Grid>
          {!isCollection && (
            <FormGroup row={true}>
              <FormControlLabel
                control={<Switch checked={show} onChange={onShowChange} />}
                label="Show on Organization Map"
              />
              <FormControlLabel
                control={<Switch checked={calc} onChange={onCalcChange} />}
                label="Calculate Statistics"
              />
            </FormGroup>
          )}
        </Grid>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleEditDetailClose} disabled={saveInProgress}>
          Cancel
        </Button>
        <Button
          onClick={handleSave}
          variant="contained"
          color="primary"
          disabled={saveInProgress}
        >
          {saveInProgress ? (
            <CircularProgress size={21} />
          ) : isUpload ? (
            'Upload'
          ) : (
            'Save'
          )}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #27
Source File: CreateQuiz.js    From quizdom with MIT License 4 votes vote down vote up
CreateQuiz = ({
	user,
	quizTitle,
	questions,

	isOpen,
	editQuizHandle
}) => {
	const [questionArray, setQuestionArray] = useState([])
	const [title, setTitle] = useState('')
	const [access, setAccesss] = useState(true)
	const [loading, setLoading] = useState('stop')
	const [quizCode, setQuizCode] = useState(null)

	const addQuestionHandle = (title, optionType, options) => {
		const arr = [...questionArray]
		arr.push({ title, optionType, options })
		setQuestionArray(arr)
	}
	useEffect(() => {
		if (quizTitle) {
			setTitle(quizTitle)
			setQuestionArray(questions)
			setAccesss(isOpen)
		}
	}, [quizTitle, questions, isOpen])

	const createQuiz = async () => {
		if (!(title.length || questionArray.length)) {
			alert('Please add title and questions.')
			return
		} else if (!title.length) {
			alert('Please add Quiz title.')
			return
		} else if (!questionArray.length) {
			alert('Please add any questions.')
			return
		}
		console.log('Quiz Creation Starts...')
		setLoading('start')
		try {
			const result = await fetch('/API/quizzes/create', {
				method: 'POST',
				body: JSON.stringify({
					title,
					uid: user.uid,
					questions: questionArray,
					isOpen: access
				}),
				headers: {
					'Content-Type': 'application/json'
				}
			})
			console.log('Quiz posted ! ')
			const body = await result.json()
			console.log('Quiz Code : ', body.quizId)
			setQuizCode(body.quizId)
		} catch (e) {
			console.log('Quiz creation error : ', e)
			setLoading('error')
		}
	}
	if (quizCode) return <Redirect push to={`/created-succesfully/${quizCode}`} />

	if (loading === 'start') return <LoadingScreen />

	return (
		<div id='main-body'>
			<div id='create-quiz-body'>
				<div className='quiz-header'>
					<input
						type='text'
						className='input-text'
						value={title}
						onChange={(e) => setTitle(e.target.value)}
						id='quiz-title'
						placeholder='Untitled Quiz'
						autoFocus
						autoComplete='off'
					/>
				</div>
				<div className='controls'>
					<AddQuestionModal addQuestionHandle={addQuestionHandle} />
					<div className='switch'>
						<Switch
							checked={access}
							onChange={(e) => setAccesss(e.target.checked)}
							color='secondary'
							name='access'
						/>
						<h4>{access ? 'Public' : 'Private'}</h4>
					</div>
				</div>
			</div>
			<div className='questionTable'>
				<QuestionsTable
					questionArray={questionArray}
					setQuestionArray={setQuestionArray}
				/>
			</div>
			<div>
				{quizTitle && (
					<button className='add-btn' onClick={() => editQuizHandle()}>
						Close
					</button>
				)}
				<button
					// disabled={!(title.length && questionArray.length)}
					className='button wd-200'
					onClick={() => {
						if (quizTitle) editQuizHandle(title, questionArray, access)
						else createQuiz()
					}}
				>
					{quizTitle ? 'Save ' : 'Create '}
					Quiz
				</button>
			</div>
		</div>
	)
}
Example #28
Source File: AddEditEducation.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditEducation = props => {
  const history = useHistory();
  const classes = useStyles();
  const studentInfo =
    auth.getUserInfo() !== null &&
    auth.getUserInfo().role.name === roleConstants.STUDENT
      ? auth.getUserInfo().studentInfo.contact.id
      : auth.getStudentIdFromCollegeAdmin();

  const { loaderStatus, setLoaderStatus } = useContext(LoaderContext);

  const EDUCATION_URL =
    strapiConstants.STRAPI_DB_URL + strapiConstants.STRAPI_EDUCATIONS;

  const [isSuccess, setIsSuccess] = useState(false);
  const [isFailed, setIsFailed] = useState(false);
  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    flag: 0,
    hideYear: false,
    isSuccess: false,
    isEditEducation: props["editEducation"] ? props["editEducation"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: 0,
    otherId: 0
  });

  const [boards, setBoards] = useState([]);
  const [academicYears, setAcademicYears] = useState([]);

  useEffect(() => {
    fetchDropdowns(strapiConstants.STRAPI_BOARDS, setBoards);
    fetchDropdowns(strapiConstants.STRAPI_ACADEMIC_YEARS, setAcademicYears);
  }, []);

  useEffect(() => {
    const marksObtained = parseInt(formState.values["marksObtained"]);
    const totalMarks = parseInt(formState.values["totalMarks"]);
    if (marksObtained > 0 && marksObtained <= totalMarks && totalMarks > 0) {
      const marks = (marksObtained / totalMarks) * 100;
      delete formState.errors[percentage];
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          percentage: marks.toFixed(2)
        },
        errors: {
          ...formState.errors
        }
      }));
    }

    let updateState = false,
      errorMessage = null;
    if (marksObtained && totalMarks && marksObtained > totalMarks) {
      updateState = true;
      errorMessage = ["Marks Obtained should be less than total Marks"];
    }

    if (marksObtained <= 0) {
      updateState = true;
      errorMessage = ["Marks should be greater than 0"];
    }

    if (totalMarks <= 0) {
      updateState = true;
      errorMessage = ["Total Marks should be greater than 0"];
    }

    if (updateState) {
      formState.errors[percentage] = errorMessage;
      delete formState.values[percentage];
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values
        },
        errors: {
          ...formState.errors
        }
      }));
    }
  }, [formState.values["marksObtained"], formState.values["totalMarks"]]);

  useEffect(() => {
    const pursuing = formState.values["pursuing"];
    if (pursuing) {
      delete formState.values["marksObtained"];
      delete formState.values["totalMarks"];
      delete formState.values["percentage"];
      delete formState.values["board"];

      const currentAcademicYear = getCurrentAcademicYear();
      const undergraduate = genericConstants.QUALIFICATION_LIST.find(
        q => q.id == "undergraduate"
      );

      if (currentAcademicYear) {
        formState.values[yearOfPassing] = currentAcademicYear.id;
      }

      if (undergraduate) {
        formState.values[qualification] = undergraduate.id;
      }

      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values
        }
      }));
    }
  }, [formState.values[pursuing]]);

  useEffect(() => {
    if (!formState.values["otherQualification"]) {
      delete formState.values["otherQualification"];
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values
        }
      }));
    }
  }, [formState.values["otherQualification"]]);

  useEffect(() => {
    if (
      formState.values[qualification] == "secondary" ||
      formState.values[qualification] == "senior_secondary" ||
      formState.values[qualification] === "graduation" ||
      formState.values[qualification] === "postgraduate" ||
      formState.values[qualification] === "diploma" ||
      formState.values[qualification] === "iti" ||
      formState.values[qualification] === "other"
    ) {
      delete formState.errors[educationYear];
      delete formState.values[educationYear];
      setFormState(formState => ({
        ...formState,
        errors: {
          ...formState.errors
        }
      }));
    }

    if (
      formState.values[qualification] == "undergraduate" ||
      formState.values[qualification] == "postgraduate"
    ) {
      delete formState.errors[board];
      delete formState.values[board];
      setFormState(formState => ({
        ...formState,
        errors: {
          ...formState.errors
        }
      }));
    }

    if (formState.values[qualification] === "other") {
      delete formState.errors[educationYear];
      delete formState.values[educationYear];
      setFormState(formState => ({
        ...formState,
        errors: {
          ...formState.errors
        }
      }));
    }
  }, [formState.values[qualification]]);

  const fetchDropdowns = (link, setList) => {
    const url =
      strapiConstants.STRAPI_DB_URL +
      link +
      "?pageSize=-1&_sort=start_date:asc";
    axios
      .get(url)
      .then(({ data }) => {
        if (link === "boards") {
          const id = data.result
            .map(board => {
              if (board.name === "Other") return board.id;
            })
            .filter(c => c);

          setFormState(formState => ({
            ...formState,
            otherId: id[0]
          }));
        }
        const list = data.result;
        setList(list);
      })
      .catch(error => {
        console.log(error);
      });
  };

  /** Part for editing Education */
  if (formState.isEditEducation && !formState.counter) {
    setLoaderStatus(true);
    if (props["dataForEdit"]) {
      if (props["dataForEdit"]["year_of_passing"]) {
        formState.values[yearOfPassing] =
          props["dataForEdit"]["year_of_passing"]["id"];
      }
      if (props["dataForEdit"]["education_year"]) {
        formState.values[educationYear] =
          props["dataForEdit"]["education_year"];
      }
      if (props["dataForEdit"]["percentage"]) {
        formState.values[percentage] = props["dataForEdit"]["percentage"];
      }
      if (props["dataForEdit"]["qualification"]) {
        formState.values[qualification] = props["dataForEdit"]["qualification"];
        if (
          formState.values[qualification] === "secondary" ||
          formState.values[qualification] === "senior_secondary"
        ) {
          EducationSchema.qualification.required = false;
          EducationSchema.qualification.validations = {};
          setFormState(formState => ({
            ...formState,
            hideYear: true
          }));
        }
      }
      if (props["dataForEdit"]["other_qualification"]) {
        formState.values["otherQualification"] =
          props["dataForEdit"]["other_qualification"];
      }
      if (props["dataForEdit"]["institute"]) {
        formState.values[institute] = props["dataForEdit"]["institute"];
      }
      if (props["dataForEdit"]["pursuing"]) {
        formState.values[pursuing] = props["dataForEdit"]["pursuing"];
      }

      if (props["dataForEdit"]["board"]) {
        formState.values[board] = props["dataForEdit"]["board"]["id"];
      }
      if (props["dataForEdit"]["other_board"]) {
        formState.values["otherboard"] = props["dataForEdit"]["other_board"];
      }

      if (props["dataForEdit"]["marks_obtained"]) {
        formState.values[marksObtained] =
          props["dataForEdit"]["marks_obtained"];
      }
      if (props["dataForEdit"]["total_marks"]) {
        formState.values[totalMarks] = props["dataForEdit"]["total_marks"];
      }

      formState.counter += 1;
    }
    setLoaderStatus(false);
  }

  /** This handle change is used to handle changes to text field */
  const handleChange = event => {
    /** TO SET VALUES IN FORMSTATE */
    event.persist();
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [event.target.name]:
          event.target.type === "checkbox"
            ? event.target.checked
            : event.target.value
      },
      touched: {
        ...formState.touched,
        [event.target.name]: true
      }
    }));

    /** This is used to remove any existing errors if present in text field */
    if (formState.errors.hasOwnProperty(event.target.name)) {
      delete formState.errors[event.target.name];
    }

    if (event.target.name == "pursuing") {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values
        },
        errors: {}
      }));
    }
  };

  /** This checks if the corresponding field has errors */
  const hasError = field => (formState.errors[field] ? true : false);

  /** Handle submit handles the submit and performs all the validations */
  const handleSubmit = event => {
    setLoaderStatus(true);
    const schema = getSchema();

    let isValid = false;
    // /** Checkif all fields are present in the submitted form */
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      schema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(formState.values, schema);
      /** Checks if the form is empty */
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      /** This is used to find out which all required fields are not filled */
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        schema
      );
      /** This sets errors by comparing it with the json schema provided */
      formState.errors = formUtilities.setErrors(formState.values, schema);
    }

    if (isValid) {
      /** CALL POST FUNCTION */
      postEducationData();
    } else {
      setFormState(formState => ({
        ...formState,
        isValid: false
      }));
    }
    setLoaderStatus(false);
    event.preventDefault();
  };

  const getSchema = () => {
    let defaultSchema = Object.assign({}, EducationSchema);
    const isPursuing = formState.values[pursuing];
    const isQualificationReq = formState.values[qualification];

    const isOtherSelected = formState.values[qualification];
    if (isOtherSelected == "other") {
      defaultSchema["otherQualification"] = {
        label: "Other qualification",
        id: "otherQualification",
        autoComplete: "otherQualification",
        required: true,
        placeholder: "Other qualification",
        autoFocus: true,
        type: "number",
        validations: {
          required: {
            value: "true",
            message: "Other qualification is required"
          }
        }
      };
      defaultSchema[educationYear] = {
        ...defaultSchema[educationYear],
        required: false
      };
    }

    if (formState.values[board] === formState.otherId) {
      defaultSchema["otherboard"] = {
        label: "Other Board",
        id: "otherboard",
        autoComplete: "otherboard",
        required: true,
        placeholder: "Other board",
        autoFocus: true,
        type: "text",
        validations: {
          required: {
            value: "true",
            message: "Other board is required"
          }
        }
      };
    }

    if (
      isQualificationReq == "secondary" ||
      isQualificationReq == "senior_secondary" ||
      isQualificationReq === "graduation" ||
      isQualificationReq === "postgraduate" ||
      isQualificationReq === "diploma" ||
      isQualificationReq === "iti" ||
      isQualificationReq === "other"
    ) {
      defaultSchema[educationYear] = {
        ...defaultSchema[educationYear],
        required: false
      };
    }

    if (
      isQualificationReq == "undergraduate" ||
      isQualificationReq == "graduation" ||
      isQualificationReq === "diploma" ||
      isQualificationReq === "iti" ||
      isQualificationReq == "postgraduate"
    ) {
      defaultSchema[board] = {
        ...defaultSchema[board],
        required: false
      };
    }

    if (isPursuing) {
      defaultSchema[percentage] = {
        ...defaultSchema[percentage],
        required: false
      };
      defaultSchema[marksObtained] = {
        ...defaultSchema[marksObtained],
        required: false
      };
      defaultSchema[totalMarks] = {
        ...defaultSchema[totalMarks],
        required: false
      };
      defaultSchema[board] = {
        ...defaultSchema[board],
        required: false
      };
    }

    return defaultSchema;
  };

  const postEducationData = async () => {
    // const id = studentInfo ? studentInfo.id : null;

    let postData = databaseUtilities.addEducation(
      formState.values[yearOfPassing],
      formState.values[educationYear],
      formState.values[percentage],
      formState.values[qualification],
      formState.values[institute],
      formState.values[pursuing],
      formState.values[board],
      formState.values["otherQualification"],
      formState.values[marksObtained],
      formState.values[totalMarks],
      formState.values["otherboard"]
    );
    // Adding student id to post data
    postData.contact = studentInfo;
    if (formState.isEditEducation) {
      serviceProviders
        .serviceProviderForPutRequest(
          EDUCATION_URL,
          formState.dataForEdit["id"],
          postData
        )
        .then(res => {
          if (formState.flag === 1) {
            history.push({
              pathname: routeConstants.VIEW_DOCUMENTS
            });
            setLoaderStatus(false);
          } else {
            history.push({
              pathname: routeConstants.VIEW_EDUCATION,
              fromEditEducation: true,
              isDataEdited: true,
              editResponseMessage: "",
              editedData: {}
            });
          }
          setLoaderStatus(false);
        })
        .catch(error => {
          console.log(error);
          history.push({
            pathname: routeConstants.VIEW_EDUCATION,
            fromEditEducation: true,
            isDataEdited: false,
            editResponseMessage: "",
            editedData: {},
            error: error.response.data ? error.response.data.message : ""
          });
          setLoaderStatus(false);
        });
    } else {
      serviceProviders
        .serviceProviderForPostRequest(EDUCATION_URL, postData)
        .then(res => {
          setIsSuccess(true);
          if (formState.flag === 1) {
            history.push({
              pathname: routeConstants.VIEW_DOCUMENTS
            });
            setLoaderStatus(false);
          } else {
            history.push({
              pathname: routeConstants.VIEW_EDUCATION,
              fromAddEducation: true,
              isDataAdded: true,
              addResponseMessage: "",
              addedData: {}
            });
          }
          setLoaderStatus(false);
        })
        .catch(error => {
          history.push({
            pathname: routeConstants.VIEW_EDUCATION,
            fromAddEducation: true,
            isDataAdded: false,
            addResponseMessage: "",
            addedData: {},
            error: error.response.data ? error.response.data.message : ""
          });
          setLoaderStatus(false);
        });
    }
  };

  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (eventName === qualification && value) {
      if (
        value.id === "secondary" ||
        value.id === "senior_secondary" ||
        value.id === "graduation" ||
        value.id === "postgraduate" ||
        value.id === "diploma" ||
        value.id === "iti" ||
        value.id === "other"
      ) {
        EducationSchema.qualification.required = false;
        EducationSchema.qualification.validations = {};
        setFormState(formState => ({
          ...formState,
          hideYear: true
        }));
      } else {
        setFormState(formState => ({
          ...formState,
          hideYear: false
        }));
      }
      if (value.id == "undergraduate") {
        EducationSchema.qualification.required = true;
        EducationSchema.qualification.validations = {
          required: {
            value: "true",
            message: "Education year is required"
          }
        };
      }
    } else {
      EducationSchema.qualification.required = true;
      EducationSchema.qualification.validations = {
        required: {
          value: "true",
          message: "Qualification is required"
        }
      };
      // setFormState(formState => ({
      //   ...formState,
      //   hideYear: false
      // }));
    }
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [eventName]: value ? value.id : ""
      },
      touched: {
        ...formState.touched,
        [eventName]: true
      }
    }));
    if (formState.errors.hasOwnProperty(eventName)) {
      delete formState.errors[eventName];
    }
  };

  const saveAndNext = event => {
    event.preventDefault();
    formState["flag"] = 1;
    handleSubmit(event);
  };

  const getCurrentAcademicYear = () => {
    return academicYears.find(ay => {
      const { start_date, end_date } = ay;

      const start = moment(start_date);
      const end = moment(end_date);
      const current = moment();

      if (moment(current).isBetween(start, end)) {
        return ay;
      }
    });
  };

  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        {isSuccess ? (
          <Alert severity="success">
            {genericConstants.ALERT_SUCCESS_BUTTON_MESSAGE}
          </Alert>
        ) : null}
        {isFailed ? (
          <Alert severity="error">
            {genericConstants.ALERT_ERROR_BUTTON_MESSAGE}
          </Alert>
        ) : null}
      </Grid>
      <Grid spacing={3} className={classes.formgrid}>
        <Card className={classes.root} variant="outlined">
          <form autoComplete="off" noValidate>
            <CardContent>
              <Grid item xs={8}>
                <Grid container className={classes.formgridInputFile}>
                  <Grid item xs={12} md={6} xl={3}>
                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <FormGroup row>
                          <FormControlLabel
                            control={
                              <Switch
                                name={pursuing}
                                checked={formState.values[pursuing] || false}
                                onChange={handleChange}
                                value={formState.values[pursuing] || false}
                              />
                            }
                            label={
                              formState.values[pursuing] === true
                                ? "Pursuing"
                                : "Passed"
                            }
                          />
                        </FormGroup>
                      </Grid>
                    </Grid>

                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <Autocomplete
                          id="year-of-passing"
                          // className={claselementrootses.}
                          options={academicYears}
                          getOptionLabel={option => option.name}
                          disabled={!!formState.values[pursuing]}
                          onChange={(event, value) => {
                            handleChangeAutoComplete(
                              yearOfPassing,
                              event,
                              value
                            );
                          }}
                          value={
                            academicYears[
                              academicYears.findIndex(function (item) {
                                return (
                                  item.id === formState.values[yearOfPassing]
                                );
                              })
                            ] || null
                          }
                          renderInput={params => (
                            <TextField
                              {...params}
                              error={hasError(yearOfPassing)}
                              label={
                                formState.values["pursuing"]
                                  ? "Current Year"
                                  : "Year of passing"
                              }
                              variant="outlined"
                              name="tester"
                              helperText={
                                hasError(yearOfPassing)
                                  ? formState.errors[yearOfPassing].map(
                                      error => {
                                        return error + " ";
                                      }
                                    )
                                  : null
                              }
                            />
                          )}
                        />
                      </Grid>
                    </Grid>

                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <Autocomplete
                          // className={classes.elementroot}
                          id="qualification-list"
                          options={genericConstants.QUALIFICATION_LIST}
                          getOptionLabel={option => option.name}
                          onChange={(event, value) => {
                            handleChangeAutoComplete(
                              qualification,
                              event,
                              value
                            );
                          }}
                          value={
                            genericConstants.QUALIFICATION_LIST[
                              genericConstants.QUALIFICATION_LIST.findIndex(
                                function (item) {
                                  return (
                                    item.id === formState.values[qualification]
                                  );
                                }
                              )
                            ] || null
                          }
                          renderInput={params => (
                            <TextField
                              {...params}
                              error={hasError(qualification)}
                              label="Qualification"
                              variant="outlined"
                              name="tester"
                              helperText={
                                hasError(qualification)
                                  ? formState.errors[qualification].map(
                                      error => {
                                        return error + " ";
                                      }
                                    )
                                  : null
                              }
                            />
                          )}
                        />
                      </Grid>
                    </Grid>
                    {formState.values[qualification] == "other" ? (
                      <Grid container spacing={3}>
                        <Grid item md={12} xs={12}>
                          <TextField
                            fullWidth
                            id="otherQualification"
                            label="Other Qualification"
                            margin="normal"
                            name="otherQualification"
                            onChange={handleChange}
                            type="text"
                            value={formState.values["otherQualification"] || ""}
                            error={hasError("otherQualification")}
                            helperText={
                              hasError("otherQualification")
                                ? formState.errors["otherQualification"].map(
                                    error => {
                                      return error + " ";
                                    }
                                  )
                                : null
                            }
                            variant="outlined"
                            // className={classes.elementroot}
                          />
                        </Grid>
                      </Grid>
                    ) : null}
                    {!formState.hideYear ? (
                      <Grid container spacing={3}>
                        <Grid item md={12} xs={12}>
                          <Autocomplete
                            id="education-list"
                            // className={classes.elementroot}
                            options={genericConstants.EDUCATIONS}
                            getOptionLabel={option => option.value}
                            onChange={(event, value) => {
                              handleChangeAutoComplete(
                                educationYear,
                                event,
                                value
                              );
                            }}
                            value={
                              genericConstants.EDUCATIONS[
                                genericConstants.EDUCATIONS.findIndex(function (
                                  item
                                ) {
                                  return (
                                    item.id === formState.values[educationYear]
                                  );
                                })
                              ] || null
                            }
                            renderInput={params => (
                              <TextField
                                {...params}
                                error={hasError(educationYear)}
                                label="Education Year"
                                // required={
                                //   !(
                                //     formState.values[qualification] ==
                                //       "secondary" ||
                                //     formState.values[qualification] ==
                                //       "senior_secondary"
                                //   )
                                // }
                                variant="outlined"
                                name="tester"
                                helperText={
                                  hasError(educationYear)
                                    ? formState.errors[educationYear].map(
                                        error => {
                                          return error + " ";
                                        }
                                      )
                                    : null
                                }
                              />
                            )}
                          />
                        </Grid>
                      </Grid>
                    ) : null}
                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <Autocomplete
                          // className={classes.elementroot}
                          id="board-list"
                          options={boards}
                          getOptionLabel={option => option.name}
                          onChange={(event, value) => {
                            handleChangeAutoComplete(board, event, value);
                          }}
                          value={
                            boards[
                              boards.findIndex(function (item) {
                                return item.id === formState.values[board];
                              })
                            ] || null
                          }
                          renderInput={params => (
                            <TextField
                              {...params}
                              error={hasError(board)}
                              label="Board"
                              variant="outlined"
                              name="tester"
                              helperText={
                                hasError(board)
                                  ? formState.errors[board].map(error => {
                                      return error + " ";
                                    })
                                  : null
                              }
                            />
                          )}
                        />
                      </Grid>
                    </Grid>
                    {formState.values[board] == formState.otherId ? (
                      <Grid container spacing={3}>
                        <Grid item md={12} xs={12}>
                          <TextField
                            fullWidth
                            id="otherboard"
                            label="Other board"
                            margin="normal"
                            name="otherboard"
                            onChange={handleChange}
                            type="text"
                            value={formState.values["otherboard"] || ""}
                            error={hasError("otherboard")}
                            helperText={
                              hasError("otherboard")
                                ? formState.errors["otherboard"].map(error => {
                                    return error + " ";
                                  })
                                : null
                            }
                            variant="outlined"
                            // className={classes.elementroot}
                          />
                        </Grid>
                      </Grid>
                    ) : null}
                    <Grid container spacing={3}>
                      <Grid item md={6} xs={12}>
                        <TextField
                          fullWidth
                          id={get(EducationSchema[marksObtained], "id")}
                          label={get(EducationSchema[marksObtained], "label")}
                          name={marksObtained}
                          onChange={handleChange}
                          type={get(EducationSchema[marksObtained], "type")}
                          value={formState.values[marksObtained] || ""}
                          error={hasError(marksObtained)}
                          helperText={
                            hasError(marksObtained)
                              ? formState.errors[marksObtained].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          variant="outlined"
                          disabled={!!formState.values[pursuing]}
                        />
                      </Grid>
                      <Grid item md={6} xs={12}>
                        <TextField
                          fullWidth
                          id={get(EducationSchema[totalMarks], "id")}
                          label={get(EducationSchema[totalMarks], "label")}
                          name={totalMarks}
                          onChange={handleChange}
                          type={get(EducationSchema[totalMarks], "type")}
                          value={formState.values[totalMarks] || ""}
                          error={hasError(totalMarks)}
                          helperText={
                            hasError(totalMarks)
                              ? formState.errors[totalMarks].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          variant="outlined"
                          disabled={!!formState.values[pursuing]}
                        />
                      </Grid>
                    </Grid>
                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <TextField
                          fullWidth
                          id={get(EducationSchema[percentage], "id")}
                          label={get(EducationSchema[percentage], "label")}
                          name={percentage}
                          onChange={handleChange}
                          type={get(EducationSchema[percentage], "type")}
                          value={formState.values[percentage] || ""}
                          error={hasError(percentage)}
                          helperText={
                            hasError(percentage)
                              ? formState.errors[percentage].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          variant="outlined"
                          disabled
                        />
                      </Grid>
                    </Grid>
                    <Grid container spacing={3}>
                      <Grid item md={12} xs={12}>
                        <TextField
                          fullWidth
                          id={institute}
                          label="Institute"
                          name={institute}
                          onChange={handleChange}
                          type="text"
                          value={formState.values[institute] || ""}
                          error={hasError(institute)}
                          helperText={
                            hasError(institute)
                              ? formState.errors[institute].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                          variant="outlined"
                          // className={classes.elementroot}
                        />
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </CardContent>
            <Grid item xs={12} className={classes.CardActionGrid}>
              <CardActions className={classes.btnspace}>
                <Grid item xs={12}>
                  <Grid item xs={12} md={6} xl={3}>
                    <Grid container spacing={3}>
                      <Grid item md={2} xs={12}>
                        <YellowButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          style={{ marginRight: "18px" }}
                          onClick={handleSubmit}
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>
                      <Grid item md={3} xs={12}>
                        <YellowButton
                          color="primary"
                          type="submit"
                          mfullWidth
                          variant="contained"
                          style={{ marginRight: "18px" }}
                          onClick={saveAndNext}
                        >
                          <span>
                            {genericConstants.SAVE_AND_NEXT_BUTTON_TEXT}
                          </span>
                        </YellowButton>
                      </Grid>
                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          to={routeConstants.VIEW_EDUCATION}
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
    </Grid>
  );
}
Example #29
Source File: AddEditUser.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditUser = props => {
  /** Initializing all the hooks */
  const classes = useStyles();
  const history = useHistory();
  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    isSuccess: false,
    isZoneBlocked: props.isZoneBlocked === "false" ? false : true,
    isRPCBlocked: props.isRPCBlocked === "false" ? false : true,
    isCollegeBlocked: props.isCollegeBlocked === "false" ? false : true,
    showPassword: props.showPassword ? props.showPassword : false,
    isEditUser: props["editUser"] ? props["editUser"] : false,
    dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
    counter: props.counter ? props.counter : 0,
    isCollegeAdmin:
      auth.getUserInfo() !== undefined &&
      auth.getUserInfo() !== null &&
      auth.getUserInfo().role !== null &&
      auth.getUserInfo().role.name !== undefined &&
      auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
        ? true
        : false
  });
  const [states, setStates] = useState(
    props.stateOption ? props.stateOption : []
  );
  const [backdrop, setBackDrop] = useState(false);
  const [zones, setZones] = useState(props.zoneOption ? props.zoneOption : []);
  const [rpcs, setRpcs] = useState(props.rpcOption ? props.rpcOption : []);
  const [colleges, setColleges] = useState(
    props.collegeOption ? props.collegeOption : []
  );
  const [roles, setRoles] = useState(props.option ? props.option : []);
  const [isDisable, setIsDisable] = useState(false);

  /** Part for editing user */
  if (formState.isEditUser && !formState.counter) {
    if (props["dataForEdit"]) {
      formState.values[password] = undefined;
      if (props["dataForEdit"]["first_name"]) {
        formState.values[firstname] = props["dataForEdit"]["first_name"];
      }
      if (props["dataForEdit"]["last_name"]) {
        formState.values[lastname] = props["dataForEdit"]["last_name"];
      }
      if (
        props["dataForEdit"]["contact"] &&
        props["dataForEdit"]["contact"]["email"]
      ) {
        formState.values[email] = props["dataForEdit"]["contact"]["email"];
      }
      if (
        props["dataForEdit"]["contact"] &&
        props["dataForEdit"]["contact"]["phone"]
      ) {
        formState.values[contact] = props["dataForEdit"]["contact"]["phone"];
      }
      if (
        props["dataForEdit"]["contact"] &&
        props["dataForEdit"]["contact"]["user"] &&
        props["dataForEdit"]["contact"]["user"]["blocked"]
      ) {
        formState.values[blocked] =
          props["dataForEdit"]["contact"]["user"]["blocked"];
      }
      if (
        props["dataForEdit"]["contact"] &&
        props["dataForEdit"]["contact"]["user"] &&
        props["dataForEdit"]["contact"]["user"]["role"] &&
        props["dataForEdit"]["contact"]["user"]["role"]["id"]
      ) {
        formState.values[role] =
          props["dataForEdit"]["contact"]["user"]["role"]["id"];
      }
      if (
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
          roleConstants.STUDENT ||
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
          roleConstants.MEDHAADMIN ||
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
          roleConstants.DEPARTMENTADMIN
      ) {
        setFormState(formState => ({
          ...formState,
          isCollegeBlocked: true,
          isRPCBlocked: true,
          isZoneBlocked: true
        }));
      } else if (
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
        roleConstants.RPCADMIN
      ) {
        setFormState(formState => ({
          ...formState,
          isCollegeBlocked: true,
          isRPCBlocked: false,
          isZoneBlocked: true
        }));
      } else if (
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
        roleConstants.ZONALADMIN
      ) {
        setFormState(formState => ({
          ...formState,
          isCollegeBlocked: true,
          isRPCBlocked: true,
          isZoneBlocked: false
        }));
      } else if (
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
        roleConstants.COLLEGEADMIN
      ) {
        setFormState(formState => ({
          ...formState,
          isCollegeBlocked: false,
          isRPCBlocked: true,
          isZoneBlocked: true
        }));
      }
      if (
        props["dataForEdit"]["contact"] &&
        props["dataForEdit"]["contact"]["user"] &&
        props["dataForEdit"]["contact"]["user"]["role"] &&
        props["dataForEdit"]["contact"]["user"]["role"]["name"] ===
          roleConstants.STUDENT
      ) {
        /** For populating state */
        if (
          props["dataForEdit"] &&
          props["dataForEdit"]["contact"] &&
          props["dataForEdit"]["contact"]["state"]
        ) {
          formState.values[state] =
            props["dataForEdit"]["contact"]["state"]["id"];
        } else {
          formState.values[state] = "";
        }

        /** For populating zone */
        if (
          props["dataForEdit"]["organization"] &&
          props["dataForEdit"]["organization"]["zone"]
        ) {
          formState.values[zone] =
            props["dataForEdit"]["organization"]["zone"]["id"];
        } else {
          formState.values[zone] = "";
        }

        /** For populating rpc */
        if (
          props["dataForEdit"]["organization"] &&
          props["dataForEdit"]["organization"]["rpc"]
        ) {
          formState.values[rpc] = props["dataForEdit"]["organization"]["rpc"];
        } else {
          formState.values[rpc] = "";
        }

        /** For populating ipc */
        if (props["dataForEdit"]["organization"]) {
          formState.values[college] =
            props["dataForEdit"]["organization"]["id"];
        } else {
          formState.values[college] = "";
        }
      } else {
        /** For populating state */
        if (
          props["dataForEdit"] &&
          props["dataForEdit"]["contact"] &&
          props["dataForEdit"]["contact"]["user"] &&
          props["dataForEdit"]["contact"]["user"]["state"]
        ) {
          formState.values[state] =
            props["dataForEdit"]["contact"]["user"]["state"]["id"];
        } else {
          formState.values[state] = "";
        }

        /** For populating zone */
        if (
          props["dataForEdit"] &&
          props["dataForEdit"]["contact"] &&
          props["dataForEdit"]["contact"]["user"] &&
          props["dataForEdit"]["contact"]["user"]["zone"]
        ) {
          formState.values[zone] =
            props["dataForEdit"]["contact"]["user"]["zone"]["id"];
        } else {
          formState.values[zone] = "";
        }

        /** For populating rpc */
        if (
          props["dataForEdit"] &&
          props["dataForEdit"]["contact"] &&
          props["dataForEdit"]["contact"]["user"] &&
          props["dataForEdit"]["contact"]["user"]["rpc"]
        ) {
          formState.values[rpc] =
            props["dataForEdit"]["contact"]["user"]["rpc"]["id"];
        } else {
          formState.values[rpc] = "";
        }

        /** For populating ipc */
        if (props["dataForEdit"]["organization"]) {
          formState.values[college] =
            props["dataForEdit"]["organization"]["id"];
        } else {
          formState.values[college] = "";
        }
      }
    }
    formState.counter += 1;
  }

  /** Use Effect function to set roles */
  useEffect(() => {
    /** Initially clear all the vlidations */
    clearValidations();

    let paramsForPageSize = {
      pageSize: -1
    };

    serviceProvider
      .serviceProviderForGetRequest(COLLEGE_URL, paramsForPageSize)
      .then(res => {
        setColleges(res.data.result);
      })
      .catch(error => {
        console.log(error);
      });

    serviceProvider
      .serviceProviderForGetRequest(STATES_URL, paramsForPageSize)
      .then(res => {
        res.data.result.map(s => {
          if (s.name === "Uttar Pradesh") {
            stateId = s.id;
            let zones_url =
              STATES_URL +
              "/" +
              stateId +
              "/" +
              strapiApiConstants.STRAPI_ZONES;

            serviceProvider
              .serviceProviderForGetRequest(zones_url)
              .then(res => {
                setZones(res.data.result);
              })
              .catch(error => {
                console.log("error", error);
              });
          }
        });
        setStates(res.data.result);
      })
      .catch(error => {
        console.log(error);
      });

    serviceProvider
      .serviceProviderForGetRequest(ROLES_URL, paramsForPageSize)
      .then(res => {
        let roles = [];
        let studentRole = null;
        for (let i in res.data.roles) {
          if (
            res.data.roles[i]["name"] !== "Admin" &&
            res.data.roles[i]["name"] !== "Authenticated" &&
            res.data.roles[i]["name"] !== "Public" &&
            res.data.roles[i]["name"] !== roleConstants.STUDENT &&
            res.data.roles[i]["name"] !== roleConstants.RPCADMIN
          ) {
            roles.push(res.data.roles[i]);
          }
          if (
            formState.isEditUser &&
            res.data.roles[i]["name"] === roleConstants.STUDENT
          ) {
            studentRole = res.data.roles[i];
          }
          if (
            formState.dataForEdit["contact"] &&
            formState.dataForEdit["contact"]["user"] &&
            formState.dataForEdit["contact"]["user"]["role"] &&
            formState.dataForEdit["contact"]["user"]["role"]["name"] ===
              roleConstants.STUDENT
          ) {
            setIsDisable(true);
          } else {
            setIsDisable(false);
          }
        }
        if (
          formState.isEditUser &&
          formState.dataForEdit["contact"]["user"]["role"]["name"] ===
            roleConstants.STUDENT
        ) {
          setRoles([studentRole]);
        } else {
          setRoles(roles);
        }
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  const handleChange = e => {
    /** TO SET VALUES IN FORMSTATE */
    e.persist();
    setFormState(formState => ({
      ...formState,

      values: {
        ...formState.values,
        [e.target.name]:
          e.target.type === "checkbox" ? e.target.checked : e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      }
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

  /** Handle change for autocomplete fields */
  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value.id
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        },
        isStateClearFilter: false
      }));
      if (eventName === college) {
        setFormState(formState => ({
          ...formState,
          values: {
            ...formState.values,
            [zone]: value.zone.id,
            [rpc]: value.rpc.id
          }
        }));
      }
      /** Get dependent roles */
      if (eventName === role) {
        let roleName = value.id;
        clearValidations();
        setValidationsForDifferentRoles(roleName);
      }
      /** This is used to remove any existing errors if present in auto complete */
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    } else {
      let setStateFilterValue = false;
      /** If we click cross for state the zone and rpc should clear off! */
      if (eventName === state) {
        /** 
        This flag is used to determine that state is cleared which clears 
        off zone and rpc by setting their value to null 
        */
        setStateFilterValue = true;
        clearZoneRpcCollege();
        /** 
        When state is cleared then clear rpc and zone 
        */
      }
      if (eventName === zone || eventName === rpc) {
        setFormState(formState => ({
          ...formState,
          isCollegeBlocked: true
        }));
        delete formState.values[college];
      }
      /** Clear dependent roles */
      if (eventName === role) {
        clearZoneRpcCollege();
        clearValidations();
      }
      setFormState(formState => ({
        ...formState,
        isStateClearFilter: setStateFilterValue
      }));
      /** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
      delete formState.values[eventName];
    }
  };

  const clearZoneRpcCollege = () => {
    setFormState(formState => ({
      ...formState,
      isCollegeBlocked: true,
      isRPCBlocked: true,
      isZoneBlocked: true
    }));
    delete formState.values[zone];
    delete formState.values[rpc];
    delete formState.values[college];
  };

  const clearValidations = () => {
    delete formState.errors[rpc];
    delete formState.errors[state];
    delete formState.errors[zone];
    delete formState.errors[college];
    UserSchema[rpc]["required"] = false;
    UserSchema[state]["required"] = false;
    UserSchema[zone]["required"] = false;
    UserSchema[college]["required"] = false;
    UserSchema[rpc]["validations"] = {};
    UserSchema[state]["validations"] = {};
    UserSchema[zone]["validations"] = {};
    UserSchema[college]["validations"] = {};
  };

  const setValidationsForDifferentRoles = (roleId, forSubmit = false) => {
    let roleName = "";
    for (let i in roles) {
      if (roles[i]["id"] === roleId) {
        roleName = roles[i]["name"];
        break;
      }
    }
    if (roleName === roleConstants.COLLEGEADMIN) {
      delete formState.errors[rpc];
      delete formState.errors[zone];
      UserSchema[state]["required"] = true;
      UserSchema[college]["required"] = true;
      UserSchema[state]["validations"] = VALIDATIONFORSTATE;
      UserSchema[college]["validations"] = VALIDATIONFORCOLLEGE;

      setFormState(formState => ({
        ...formState,
        isCollegeBlocked: false,
        isRPCBlocked: true,
        isZoneBlocked: true
      }));
    } else if (roleName === roleConstants.RPCADMIN) {
      delete formState.errors[zone];
      delete formState.errors[college];
      UserSchema[rpc]["required"] = true;
      UserSchema[state]["required"] = true;
      UserSchema[rpc]["validations"] = VALIDATIONFORRPC;
      UserSchema[state]["validations"] = VALIDATIONFORSTATE;
      setFormState(formState => ({
        ...formState,
        isCollegeBlocked: true,
        isRPCBlocked: false,
        isZoneBlocked: true
      }));
    } else if (roleName === roleConstants.ZONALADMIN) {
      delete formState.errors[state];
      delete formState.errors[zone];
      UserSchema[state]["required"] = true;
      UserSchema[zone]["required"] = true;
      UserSchema[state]["validations"] = VALIDATIONFORSTATE;
      UserSchema[zone]["validations"] = VALIDATIONFORZONE;
      setFormState(formState => ({
        ...formState,
        isCollegeBlocked: true,
        isRPCBlocked: true,
        isZoneBlocked: false
      }));
    } else if (
      roleName === roleConstants.MEDHAADMIN ||
      roleName === roleConstants.DEPARTMENTADMIN
    ) {
      clearValidations();
      setFormState(formState => ({
        ...formState,
        isCollegeBlocked: true,
        isRPCBlocked: true,
        isZoneBlocked: true
      }));
    } else if (roleName === roleConstants.STUDENT) {
      clearValidations();
      setFormState(formState => ({
        ...formState,
        isCollegeBlocked: true,
        isRPCBlocked: true,
        isZoneBlocked: true
      }));
    }
  };
  const handleSubmit = event => {
    event.preventDefault();
    setBackDrop(true);
    formState.values[state] = stateId;
    if (formState.isEditUser) {
      UserSchema[password]["required"] = false;
      UserSchema[password]["validations"] = {
        validatePasswordMinLength: {
          value: "true",
          message: "Password is too short"
        }
      };
      if (formState.values[role]) {
        setValidationsForDifferentRoles(formState.values[role], true);
      }
    } else {
      UserSchema[password]["required"] = true;
      UserSchema[password]["validations"] = {
        required: {
          value: "true",
          message: "password is required"
        },
        validatePasswordMinLength: {
          value: "true",
          message: "Password is too short"
        }
      };
    }
    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      UserSchema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(formState.values, UserSchema);
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      /** This is used to find out which all required fields are not filled */
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        UserSchema
      );
      formState.errors = formUtilities.setErrors(formState.values, UserSchema);
    }
    if (isValid) {
      /** CALL POST FUNCTION */
      postUserData();

      /** Call axios from here */
      setFormState(formState => ({
        ...formState,
        isValid: true
      }));
    } else {
      setBackDrop(false);
      setFormState(formState => ({
        ...formState,
        isValid: false
      }));
    }
  };

  const postUserData = async () => {
    setBackDrop(true);
    let postData = databaseUtilities.addUser(
      formState.values[contact],
      formState.values[email],
      formState.values[firstname],
      formState.values[lastname],
      formState.values[password] ? formState.values[password] : undefined,
      formState.values[contact],
      formState.values[blocked] ? formState.values[blocked] : false,
      formState.values[state] ? formState.values[state] : null,
      formState.values[zone] ? formState.values[zone] : null,
      formState.values[rpc] ? formState.values[rpc] : null,
      formState.values[college] ? formState.values[college] : null,
      formState.values[role] ? formState.values[role] : null
    );
    if (formState.isEditUser) {
      let EDIT_USER_URL =
        strapiApiConstants.STRAPI_DB_URL +
        strapiApiConstants.STRAPI_CONTACT_URL;
      let EDIT_URL = strapiApiConstants.STRAPI_EDIT_STUDENT + "?fromuser=true";
      serviceProvider
        .serviceProviderForPutRequest(
          EDIT_USER_URL,
          formState.dataForEdit.contact["id"],
          postData,
          EDIT_URL
        )
        .then(res => {
          history.push({
            pathname: routeConstants.MANAGE_USER,
            fromeditUser: true,
            isDataEdited: true,
            editedUserName: res.data.result,
            editResponseMessage: "",
            editedData: {}
          });
          setBackDrop(false);
        })
        .catch(error => {
          let errorMessage;

          if (
            error.response !== undefined &&
            error.response.status !== undefined &&
            error.response.status === 400
          ) {
            if (error.response.data["message"]) {
              errorMessage = error.response.data["message"];
            }
          }
          history.push({
            pathname: routeConstants.MANAGE_USER,
            fromeditUser: true,
            isDataEdited: false,
            editResponseMessage: errorMessage ? errorMessage : "",
            editedData: {}
          });
          setBackDrop(false);
        });
    } else {
      serviceProvider
        .serviceProviderForPostRequest(USERS_URL, postData)
        .then(res => {
          history.push({
            pathname: routeConstants.MANAGE_USER,
            fromAddUser: true,
            isDataAdded: true,
            addedUserName: res.data.user,
            addResponseMessage: "",
            addedData: {}
          });
          setBackDrop(false);
        })
        .catch(error => {
          let errorMessage;

          if (
            error.response !== undefined &&
            error.response.status !== undefined &&
            error.response.status === 400
          ) {
            if (error.response.data["message"]) {
              errorMessage = error.response.data["message"];
            }
          }
          history.push({
            pathname: routeConstants.MANAGE_USER,
            fromAddUser: true,
            isDataAdded: false,
            addResponseMessage: errorMessage ? errorMessage : "",
            addedData: {}
          });
        });
      setBackDrop(false);
    }
  };

  const handleClickShowPassword = () => {
    setFormState({ ...formState, showPassword: !formState.showPassword });
  };

  const handleMouseDownPassword = event => {
    event.preventDefault();
  };

  const hasError = field => (formState.errors[field] ? true : false);
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          {formState.isEditUser
            ? genericConstants.EDIT_USER_TITLE
            : genericConstants.ADD_USER_TITLE}
        </Typography>
      </Grid>
      <Grid spacing={3}>
        <Card>
          <form
            id="userForm"
            autoComplete="off"
            noValidate
            onSubmit={handleSubmit}
          >
            <CardContent>
              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={6} xs={12}>
                    <TextField
                      id={get(UserSchema[firstname], "id")}
                      label={get(UserSchema[firstname], "label")}
                      placeholder={get(UserSchema[firstname], "placeholder")}
                      name={firstname}
                      value={formState.values[firstname] || ""}
                      error={hasError(firstname)}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError(firstname)
                          ? formState.errors[firstname].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <TextField
                      id={get(UserSchema[lastname], "id")}
                      label={get(UserSchema[lastname], "label")}
                      placeholder={get(UserSchema[lastname], "placeholder")}
                      name={lastname}
                      value={formState.values[lastname] || ""}
                      error={hasError(lastname)}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError(lastname)
                          ? formState.errors[lastname].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <TextField
                      id={get(UserSchema[email], "id")}
                      label={get(UserSchema[email], "label")}
                      placeholder={get(UserSchema[email], "placeholder")}
                      name={email}
                      value={formState.values[email] || ""}
                      error={hasError(email)}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError(email)
                          ? formState.errors[email].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <TextField
                      id={get(UserSchema[contact], "id")}
                      label={get(UserSchema[contact], "label")}
                      placeholder={get(UserSchema[contact], "placeholder")}
                      name={contact}
                      value={formState.values[contact] || ""}
                      error={hasError(contact)}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      helperText={
                        hasError(contact)
                          ? formState.errors[contact].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id={get(UserSchema[role], "id")}
                      className={classes.root}
                      options={roles}
                      disabled={isDisable}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(role, event, value);
                      }}
                      value={
                        roles[
                          roles.findIndex(function (item, i) {
                            return item.id === formState.values[role];
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError(role)}
                          label={get(UserSchema[role], "label")}
                          placeholder={get(UserSchema[role], "placeholder")}
                          variant="outlined"
                          name="tester"
                          helperText={
                            hasError(role)
                              ? formState.errors[role].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Grid>
              <Divider className={classes.divider} />
              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={6} xs={12}>
                    <FormControl variant="outlined" fullWidth>
                      <InputLabel
                        htmlFor="outlined-adornment-password"
                        fullWidth
                        error={hasError(password)}
                      >
                        {get(UserSchema[password], "label")}
                      </InputLabel>
                      <OutlinedInput
                        id={get(UserSchema[password], "id")}
                        placeholder={get(UserSchema[password], "placeholder")}
                        name={password}
                        required
                        fullWidth
                        error={hasError(password)}
                        type={formState.showPassword ? "text" : "password"}
                        value={formState.values[password] || ""}
                        onChange={handleChange}
                        endAdornment={
                          <InputAdornment
                            position="end"
                            error={hasError(password)}
                          >
                            <IconButton
                              aria-label="toggle password visibility"
                              onClick={handleClickShowPassword}
                              onMouseDown={handleMouseDownPassword}
                              edge="end"
                            >
                              {formState.showPassword ? (
                                <Visibility />
                              ) : (
                                <VisibilityOff />
                              )}
                            </IconButton>
                          </InputAdornment>
                        }
                        labelWidth={70}
                      />
                      <FormHelperText error={hasError(password)}>
                        {hasError(password)
                          ? formState.errors[password].map(error => {
                              return error + " ";
                            })
                          : null}
                      </FormHelperText>
                    </FormControl>
                  </Grid>
                  <Grid item md={4} xs={12}>
                    <FormGroup row>
                      <FormControlLabel
                        id="blocked"
                        control={
                          <Switch
                            id="blocked"
                            name={blocked}
                            checked={formState.values[blocked] || false}
                            onChange={handleChange}
                            value={formState.values[blocked] || false}
                            error={hasError(blocked)}
                            helperText={
                              hasError(blocked)
                                ? formState.errors[blocked].map(error => {
                                    return error + " ";
                                  })
                                : null
                            }
                          />
                        }
                        label={formState.values[blocked] ? "Unblock" : "Block"}
                      />
                    </FormGroup>
                  </Grid>
                </Grid>
              </Grid>

              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id={get(UserSchema[zone], "id")}
                      className={classes.root}
                      disabled={isDisable || formState.isZoneBlocked}
                      options={zones}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(zone, event, value);
                      }}
                      value={
                        isDisable || formState.isZoneBlocked
                          ? null
                          : zones[
                              zones.findIndex(function (item, i) {
                                return item.id === formState.values[zone];
                              })
                            ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          label={get(UserSchema[zone], "label")}
                          placeholder={get(UserSchema[zone], "placeholder")}
                          variant="outlined"
                          error={hasError(zone)}
                          helperText={
                            hasError(zone)
                              ? formState.errors[zone].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id={get(UserSchema[college], "id")}
                      className={classes.root}
                      disabled={isDisable || formState.isCollegeBlocked}
                      options={colleges}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete(college, event, value);
                      }}
                      value={
                        isDisable || formState.isCollegeBlocked
                          ? null
                          : colleges[
                              colleges.findIndex(function (item, i) {
                                return item.id === formState.values[college];
                              })
                            ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          label={get(UserSchema[college], "label")}
                          placeholder={get(UserSchema[college], "placeholder")}
                          variant="outlined"
                          error={hasError(college)}
                          helperText={
                            hasError(college)
                              ? formState.errors[college].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Grid>
            </CardContent>
            <Grid item xs={12} className={classes.CardActionGrid}>
              <CardActions className={classes.btnspace}>
                <Grid item xs={12}>
                  <Grid item xs={12} md={6} xl={3}>
                    <Grid container spacing={3}>
                      <Grid item md={2} xs={12}>
                        <YellowButton
                          type="submit"
                          color="primary"
                          variant="contained"
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>
                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          to={routeConstants.MANAGE_USER}
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={backdrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}