surveyjs / survey-library

Free JavaScript form builder library with integration for React, Angular, Vue, jQuery, and Knockout.
https://surveyjs.io/form-library
MIT License
4.13k stars 804 forks source link

It is impossible to override question error rendering for a particular survey #8189

Closed andrewtelnov closed 5 months ago

andrewtelnov commented 5 months ago

The question was asked in SurveyJS support forum: Customize Error message in preview screen of survey creator.

tsv2013 commented 5 months ago

We decided to implement an ability to override question error component rendering

tsv2013 commented 5 months ago

I've implemented functionality allowing to override question error rendering for any survey.

In order to do it it survey creator preview you need to use the declare custom component for error visualization:

class CustomQuestionError extends React.Component {
  render() {
    const owner = this.props.error.errorOwner;
    const question = !!owner && owner.isQuestion ? owner : undefined;
    const clickMeFunc = () => alert(!!question && !question.isEmpty() ? question.value : "No value");
    return (
      <div>
        <div>A custom text</div>
        <span className={this.props.cssClasses.error.icon || undefined} aria-hidden="true" />
        <span className={this.props.cssClasses.error.item || undefined}>
          <SurveyReact.SurveyLocStringViewer locStr={this.props.error.locText} />
        </span>
        <button onClick={clickMeFunc}>Click Me...</button>
      </div>
    );
  }
}

SurveyReact.ReactElementFactory.Instance.registerElement(
  "my-preview-error",
  (props) => {
    return React.createElement(CustomQuestionError, props);
  }
);

and set the questionErrorComponent property for survey used in preview tab:

creator.onSurveyInstanceCreated.add((sender, options) => {
  if (options.reason = "preview") {
    options.survey.questionErrorComponent = "my-preview-error";
  }
});