Home > OS >  Disable save until all categories are selected
Disable save until all categories are selected

Time:11-18

We have this file list and we added a file category column. We want to disable the save button until all files have a category but I've never done this before where I checked for the same value each time. Any suggestions? Currently this is what we have which works for the first file category but will enable as soon as the first category is selected.

 public state = {
    attachedFile: this.attachedFile,
    fileCategory: this.fileCategory,
    isDirty: false,
    selectedCategory: '',
    selectedFile: [] as any[],
    submitDisabled: true,
    well: new IWell(),
    wellId: this.props.match.params.wellId
};

private handleInputChange = (index: number) => (event: any) => {
    const well = this.state.well;
    well.files[index].fileCategory = event.target.value;
      this.setState({
      isDirty: true,
      submitDisabled: !this.state.well.files,
      well
      });
  }

public renderDropdown = (category: string, index: number) => () => {
    return (
        <FormGroup>
            <EInput
                type="select"
                name="Category"
                value={this.state.well.files[index].fileCategory}
                onChange={this.handleInputChange(index)}
            >
                <option value="" /> 
                <option value="Not Categorized">Not Categorized</option>
                <option value="Signed Documents">Signed Documents</option>
                <option value="Unsigned Documents">Unsigned Documents</option>
                <option value="3rd Party Documents">3rd Party Documents</option>
                <option value="General Well Info">General Well Info</option>
            </EInput>
        </FormGroup>
    );
}

<EButton disabled={this.state.submitDisabled } color="primary" name="save" onClick={this.updateWellModel}>Save</EButton>}

CodePudding user response:

You just need to change your handleInputChange() function to check to make sure every file in this.state.well.files has a populated fileCategory property. If not, you should keep the save button disabled.

Put another way, if any of the files don't have a fileCategory, disable the button.

private handleInputChange = (index: number) => (event: any) => {
    const { well } = this.state;
    const { value } = event.target;
    const isCategoryChanged = well.files[index].fileCategory !== value;
    const someFilesAreMissingCategory = well.files.some(file => !file.fileCategory);
    well.files[index].fileCategory = value;
    this.setState((state) => {
      return {
        isDirty: state.isDirty || isCategoryChanged,
        submitDisabled: someFilesAreMissingCategory,
      };
    });
  }

I also fixed an issue where if you select the same category for the dropdown when the form is not dirty, it would previously mark the form as dirty even though no data has changed. My version addresses that.

  • Related