AG Grid: Better way for validation row - valueSetter?

后端 未结 3 444
时光取名叫无心
时光取名叫无心 2020-12-11 14:01

Is there a better way to validate a row in ag-grid than with valueSetter?

I can achieve the validation with that but I am not sure, if ther

3条回答
  •  感情败类
    2020-12-11 14:26

    You could override the valueSetter and call the grid api transaction update instead.

    Here is pseudo-code that shows how you could implement this.

    valueSetter: params => {
      validate(params.newValue, onSuccess, onFail);
      return false;
    };
    
    validate = (newvalue, success, fail) => {
      if (isValid(newValue)) {
        success();
      } else {
        fail();
      }
    };
    
    onSuccess = () => {
      // do transaction update to update the cell with the new value
    };
    
    onFail = () => {
      // update some meta data property that highlights the cell signalling that the value has failed to validate
    };
    

    This way you can also do asynchronous validation. Here is a real example of an async value setter that has success, failure, and while validating handlers that do transaction updates when validation is done.

    const asyncValidator = (
      newValue,
      validateFn,
      onWhileValidating,
      onSuccess,
      _onFail
    ) => {
      onWhileValidating();
      setTimeout(function() {
        if (validateFn(newValue)) {
          onSuccess();
        } else {
          _onFail();
        }
      }, 1000);
    };
    
    const _onWhileValidating = params => () => {
      let data = params.data;
      let field = params.colDef.field;
    
      data[field] = {
        ...data[field],
        isValidating: true
      };
      params.api.applyTransaction({ update: [data] });
    };
    
    const _onSuccess = params => () => {
      let data = params.data;
      let field = params.colDef.field;
    
      data[field] = {
        ...data[field],
        isValidating: false,
        lastValidation: true,
        value: params.newValue
      };
      params.api.applyTransaction({ update: [data] });
    };
    
    const _onFail = params => () => {
      let data = params.data;
      let field = params.colDef.field;
    
      data[field] = {
        ...data[field],
        isValidating: false,
        lastValidation: params.newValue
      };
      params.api.applyTransaction({ update: [data] });
    };
    
    const asyncValidateValueSetter = validateFn => params => {
      asyncValidator(
        params.newValue,
        validateFn,
        _onWhileValidating(params),
        _onSuccess(params),
        _onFail(params)
      );
      return false;
    };
    

    Here is a code runner example showing this in action: https://stackblitz.com/edit/async-validation-ag-grid-final

提交回复
热议问题