---
title: Generate Domain Model Code
product: Survey Creator
description: With SurveyJS, you can collect data from your clients and users without having to build a client-side app with multiple pages for each form. View a free demo for JavaScript to learn how to generate form definition for a domain model in JSON and edit both of them in a no-code visual editor.
framework: Vue 3
source: https://surveyjs.io/survey-creator/examples/create-domain-models/vue3js
index: https://surveyjs.io/survey-creator/examples/overview.md
---

# Generate Domain Model Code (Vue 3)

This example demonstrates how to generate server-side domain model code based on a client-side survey JSON schema. This functionality is part of a wider use case described in the following help topic: [No-code Editor for Domain Models](https://surveyjs.io/documentation/no-code-editor-for-domain-models).

To generate domain model code in your application, implement a text parser that converts JSON to the server-side code language you prefer (C# in this demo). View the `codegenerator.js` file to see the implementation.

In this demo, you can see the generated domain model code under the Domain Model Code tab in Survey Creator. To implement this UI, create a component that renders a `<textarea>` and call the [`addTab(tabOptions)`](https://surveyjs.io/survey-creator/documentation/api-reference/survey-creator#addTab) method on a [`SurveyCreatorModel`](https://surveyjs.io/survey-creator/documentation/api-reference/survey-creator) instance to register the component as a plugin.

Domain model property names are converted from form field names, so you need to ensure against unsupported symbols. Handle Survey Creator's [`onPropertyDisplayCustomError`](https://surveyjs.io/survey-creator/documentation/api-reference/survey-creator#onPropertyDisplayCustomError) event to validate the names.

## Files

### `public/index.html`

```html
<div id="app" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0;"></div>
```

### `src/ServerCode.vue`

```html
<template>
    <textarea class="generatortextarea">
        {{serverCode}}
    </textarea>
</template>
<script lang="ts" setup>
import type { SurveyCreatorModel } from "survey-creator-core";
import { generateDomainModelCode } from "./codegenerator";

const props = defineProps<{
  model: SurveyCreatorModel;
}>();

const serverCode = generateDomainModelCode(props.model.survey);
</script>
```

### `src/codegenerator.js`

```js
function isNameCorrect(name) {
    return /^@?[a-zA-Z_]\w*(\.@?[a-zA-Z_]\w*)*$/.test(name);
}

function isListQuestionType(el) {
    return ["paneldynamic", "matrixdynamic", "matrixdropdown"].indexOf(el.getType()) > -1;
}

function getNestedItemClassName(name) {
    return name + "Item";
}

function getElementTypeName(el) {
    if (isListQuestionType(el)) return "IList<" + getNestedItemClassName(el.name) + ">";
    if (el.getType() === "text") {
        if (el.inputType === "number") return "int";
        if (el.inputType === "date" || el.inputType === "localedate") return "DateTime";
    }
    if (el.getType() === "boolean") return "bool"
    return "string";
}
function getCodePadding() { return "    "; }

function generateClassByElements(className, elements, lines) {
    lines.push("public class " + className + " {");
    elements.forEach(el => {
        if (el.isQuestion || el.getType() === "matrixdropdowncolumn") {
            lines.push(getCodePadding() + getElementTypeName(el) + " " + el.name + " { get; set; }")
        }
    });
    lines.push("}")
}

export function generateDomainModelCode(survey) {
    const lines = [];
    generateClassByElements(survey.name, survey.getAllQuestions(), lines);
    survey.getAllQuestions().forEach(q => {
        if (!isListQuestionType(q)) return;
        if (q.getType() === "paneldynamic") {
            lines.push("");
            generateClassByElements(getNestedItemClassName(q.name), q.elements, lines);
        } else {
            lines.push("");
            generateClassByElements(getNestedItemClassName(q.name), q.columns, lines);
        }
    });
    return lines.join("\n");
}
```

### `src/survey_json.js`

```js
export const formJSON = {
  "name": "PatientAssessment",
  "title": "Patient Assessment Form",
  "checkErrorsMode": "onValueChanged",
  "questionErrorLocation": "bottom",
  "pages": [
    {
      "name": "PatientInformation",
      "title": "Patient information",
      "navigationTitle": "Patient information",
      "elements": [
        {
          "type": "panel",
          "name": "patient-information",
          "title": "All fields with an asterisk (*) are required fields, and must be filled out in order to process the information in strict confidentiality.",
          "elements": [
            {
              "type": "text",
              "name": "FirstName",
              "title": "First name",
              "isRequired": true
            },
            {
              "type": "text",
              "name": "LastName",
              "startWithNewLine": false,
              "title": "Last name",
              "isRequired": true
            },
            {
              "type": "text",
              "name": "SSN",
              "title": "Social Security number",
              "requiredErrorText": "You SSN must be a 9-digit number.",
              "isRequired": true
            },
            {
              "type": "text",
              "name": "BirthDate",
              "startWithNewLine": false,
              "title": "Date of birth",
              "isRequired": true,
              "inputType": "date"
            },
            {
              "type": "text",
              "name": "Concerns",
              "title": "List any concerns you want to talk about during your visit"
            }
          ]
        }
      ]
    },
    {
      "name": "HealthHistory",
      "title": "Health history",
      "navigationTitle": "Health history",
      "elements": [
        {
          "type": "panel",
          "name": "health-history",
          "elements": [
            {
              "type": "boolean",
              "name": "Diabetes",
              "title": "Do you have diabetes?",
              "startWithNewLine": false
            },
            {
              "type": "boolean",
              "name": "HighBloodPressure",
              "title": "High blood pressure?",
              "startWithNewLine": false
            },
            {
              "type": "boolean",
              "name": "HighCholesterol",
              "title": "High cholesterol?",
              "startWithNewLine": false
            },
            {
              "type": "comment",
              "name": "OtherHealthConditions",
              "title": "Do you have other health conditions?"
            }
          ]
        }
      ]
    },
    {
      "name": "SocialHistory",
      "title": "Social history",
      "navigationTitle": "Social history",
      "elements": [
        {
          "type": "panel",
          "name": "social-history",
          "elements": [
            {
              "type": "panel",
              "name": "smoking",
              "elements": [
                {
                  "type": "radiogroup",
                  "name": "Cigarettes",
                  "title": "Do you smoke cigarettes?",
                  "choices": [
                    {
                      "value": "never",
                      "text": "Never"
                    },
                    {
                      "value": "yes",
                      "text": "Yes"
                    },
                    {
                      "value": "quit",
                      "text": "Quit"
                    }
                  ]
                },
                {
                  "type": "text",
                  "name": "CigarettesPacksPerDay",
                  "visibleIf": "{Cigarettes} = 'yes'",
                  "title": "How many packs a day?",
                  "inputType": "number",
                  "min": 0
                },
                {
                  "name": "date-quit",
                  "title": "CigarettesDateQuit",
                  "inputType": "date",
                  "maxValueExpression": "today()",
                  "visibleIf": "{Cigarettes} = 'quit'"
                },
                {
                  "name": "CigarettesYearsSmoked",
                  "title": "Years smoked",
                  "inputType": "number",
                  "min": 0,
                  "visibleIf": "{Cigarettes} = 'quit'"
                },
                {
                  "type": "boolean",
                  "name": "CigarettesVape",
                  "title": "Do you vape (e-cigarettes)?"
                }
              ]
            },
            {
              "type": "panel",
              "name": "alcohol-use-history",
              "elements": [
                {
                  "type": "boolean",
                  "name": "Alcohol",
                  "title": "Do you drink alcohol?"
                },
                {
                  "type": "text",
                  "name": "DrinksPerWeek",
                  "inputType": "number",
                  "visibleIf": "{Alcohol} = true",
                  "title": "How many drinks per week?"
                }
              ],
              "startWithNewLine": false
            },
            {
              "type": "panel",
              "name": "drug-use-history",
              "elements": [
                {
                  "type": "checkbox",
                  "name": "RecreationalDrugs",
                  "title": "Do you use recreational drugs?",
                  "choices": [
                    {
                      "value": "rarely",
                      "text": "Rarely"
                    },
                    {
                      "value": "marijuana",
                      "text": "Marijuana"
                    },
                    {
                      "value": "cocaine",
                      "text": "Cocaine"
                    },
                    {
                      "value": "opioids",
                      "text": "Opioids"
                    }
                  ],
                  "showOtherItem": true,
                  "otherPlaceholder": "Please specify... ",
                  "otherText": "Other",
                  "showNoneItem": true,
                  "noneText": "Never",
                  "colCount": 3
                },
                {
                  "type": "text",
                  "name": "DrugUseTimesPerMonth",
                  "visibleIf": "{RecreationalDrugs} anyof ['rarely', 'marijuana', 'cocaine', 'opioids', 'other']",
                  "title": "How many times per month",
                  "description": "If you take different types of drugs, please specify the frequency of use for each in a 'drug - # times/month' format."
                }
              ]
            },
            {
              "type": "panel",
              "name": "personal-info",
              "elements": [
                {
                  "type": "dropdown",
                  "name": "Education",
                  "title": "What is your highest level of education completed?",
                  "choices": [
                    {
                      "value": "high-school",
                      "text": "High School"
                    },
                    {
                      "value": "trade-school",
                      "text": "Trade School"
                    },
                    {
                      "value": "college",
                      "text": "College"
                    },
                    {
                      "value": "post-graduate",
                      "text": "Post-graduate degree(s)"
                    }
                  ]
                },
                {
                  "type": "dropdown",
                  "name": "MaritalStatus",
                  "title": "What is your marital status?",
                  "choices": [
                    {
                      "value": "married",
                      "text": "Married"
                    },
                    {
                      "value": "partnership",
                      "text": "Partnership"
                    },
                    {
                      "value": "divorced",
                      "text": "Divorced"
                    },
                    {
                      "value": "separated",
                      "text": "Separated"
                    },
                    {
                      "value": "single",
                      "text": "Single"
                    },
                    {
                      "value": "widow",
                      "text": "Widow(er)"
                    }
                  ]
                },
                {
                  "type": "panel",
                  "name": "sexual-life",
                  "elements": [
                    {
                      "type": "boolean",
                      "name": "SexuallyActive",
                      "title": "Are you sexually active?"
                    },
                    {
                      "type": "text",
                      "name": "SexualPartnersNumber",
                      "title": "How many sexual partners do you have?",
                      "inputType": "number",
                      "min": 0
                    },
                    {
                      "type": "radiogroup",
                      "name": "SexualPartnersGender",
                      "titleLocation": "hidden",
                      "choices": [
                        {
                          "value": "men",
                          "text": "Men"
                        },
                        {
                          "value": "women",
                          "text": "Women"
                        },
                        {
                          "value": "both",
                          "text": "Both"
                        }
                      ],
                      "colCount": 3
                    },
                    {
                      "type": "boolean",
                      "name": "Contraception",
                      "title": "Do you use contraception?"
                    },
                    {
                      "type": "comment",
                      "name": "ContraceptionComment",
                      "title": "What type of contraception do you use?",
                      "visibleIf": "{Contraception} = true"
                    }
                  ]
                }
              ]
            },
            {
              "type": "panel",
              "name": "employment-exercises-children",
              "startWithNewLine": false,
              "elements": [
                {
                  "type": "radiogroup",
                  "name": "Employment",
                  "title": "Are you employed?",
                  "choices": [
                    {
                      "value": "yes",
                      "text": "Yes"
                    },
                    {
                      "value": "no",
                      "text": "No"
                    },
                    {
                      "value": "retired",
                      "text": "Retired"
                    }
                  ],
                  "colCount": 3
                },
                {
                  "type": "comment",
                  "name": "EmploymentComment",
                  "title": "Type of work"
                },
                {
                  "type": "panel",
                  "name": "physical-activity",
                  "elements": [
                    {
                      "type": "boolean",
                      "name": "DoExercise",
                      "title": "Do you exercise?"
                    },
                    {
                      "type": "text",
                      "name": "ExerciseActivityType",
                      "title": "Type of activity",
                      "visibleIf": "{DoExercise} = true"
                    },
                    {
                      "type": "text",
                      "name": "ExerciseActivityFrequency",
                      "title": "How often?",
                      "visibleIf": "{DoExercise} = true"
                    },
                    {
                      "type": "text",
                      "name": "ExerciseActivityDuration",
                      "title": "How long per activity?",
                      "visibleIf": "{DoExercise} = true"
                    }
                  ]
                },
                {
                  "type": "panel",
                  "name": "children",
                  "elements": [
                    {
                      "type": "boolean",
                      "name": "HaveChildren",
                      "title": "Do you have children?"
                    },
                    {
                      "type": "text",
                      "name": "ChildrenNumber",
                      "title": "# of children",
                      "inputType": "number",
                      "visibleIf": "{HaveChildren} = true"
                    },
                    {
                      "type": "text",
                      "name": "ChildrenAges",
                      "title": "Their ages",
                      "visibleIf": "{HaveChildren} = true"
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "name": "SurgicalHistory",
      "title": "Surgical history / recent hospitalizations",
      "navigationTitle": "Surgical history",
      "elements": [
        {
          "type": "comment",
          "name": "SurgeryDescription",
          "title": "Date and type of surgery / procedure"
        }
      ]
    },
    {
      "name": "FamilyHistory",
      "title": "Family history",
      "navigationTitle": "Family history",
      "elements": [
        {
          "type": "matrixdynamic",
          "name": "FamilyHistory",
          "cellType": "text",
          "titleLocation": "hidden",
          "rowCount": 1,
          "columns": [
            {
              "name": "Relation"
            },
            {
              "name": "HealthConditions",
              "title": "Health conditions"
            },
            {
              "name": "CancerHistory",
              "title": "Family history of cancer"
            }
          ]
        }
      ]
    },
    {
      "name": "PreventiveCare",
      "title": "Preventive care",
      "navigationTitle": "Preventive care",
      "elements": [
        {
          "type": "panel",
          "name": "preventive-care",
          "elements": [
            {
              "type": "matrixdynamic",
              "name": "RecentShots",
              "title": "Recent shots from a doctor or pharmacist",
              "rowCount": 0,
              "columns": [
                {
                  "name": "Name",
                  "cellType": "dropdown",
                  "isRequired": true,
                  "choices": [
                    {
                      "value": "flu",
                      "text": "Flu"
                    },
                    {
                      "value": "shingles",
                      "text": "Shingles"
                    },
                    {
                      "value": "pneumonia",
                      "text": "Pneumonia"
                    },
                    {
                      "value": "tetanus",
                      "text": "Tetanus"
                    },
                    {
                      "value": "other",
                      "text": "Other"
                    }
                  ]
                },
                {
                  "name": "Date",
                  "cellType": "text",
                  "inputType": "date"
                },
                {
                  "name": "Place",
                  "cellType": "text"
                }
              ]
            },
            {
              "type": "matrixdynamic",
              "name": "RecentTests",
              "title": "Recent tests or procedures",
              "rowCount": 0,
              "columns": [
                {
                  "name": "Name",
                  "isRequired": true,
                  "cellType": "dropdown",
                  "choices": [
                    {
                      "value": "colonoscopy",
                      "text": "Colonoscopy"
                    },
                    {
                      "value": "cologuard",
                      "text": "Cologuard"
                    },
                    {
                      "value": "mammogram",
                      "text": "Mammogram"
                    },
                    {
                      "value": "pap",
                      "text": "PAP"
                    },
                    {
                      "value": "other",
                      "text": "Other"
                    }
                  ]
                },
                {
                  "name": "Date",
                  "cellType": "text",
                  "inputType": "date"
                },
                {
                  "name": "Place",
                  "cellType": "text"
                }
              ]
            },
            {
              "type": "matrixdynamic",
              "name": "Specialists",
              "cellType": "text",
              "columns": [
                {
                  "name": "Provider",
                  "title": "Provider's first and last name"
                },
                {
                  "name": "Speciality",
                  "title": "Speciality"
                },
                {
                  "name": "City",
                  "title": "Town/City"
                }
              ],
              "rowCount": 1
            },
            {
              "type": "matrixdynamic",
              "name": "Medications",
              "cellType": "text",
              "rowCount": 1,
              "columns": [
                {
                  "name": "Name"
                },
                {
                  "name": "Dose"
                },
                {
                  "name": "TimesPerDay",
                  "title": "Times per day"
                }
              ]
            },
            {
              "type": "matrixdynamic",
              "name": "Allergies",
              "cellType": "text",
              "rowCount": 1,
              "columns": [
                {
                  "name": "Type"
                },
                {
                  "name": "Reaction"
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "name": "Symptoms",
      "elements": [
        {
          "type": "tagbox",
          "name": "Symptoms",
          "title": "Please select any symptoms you have now or have had in the past month.",
          "choices": [
            "Fever",
            "Chills",
            "Feeling poorly",
            "Feeling tired",
            "Weight gain",
            "Weight loss",
            "Chest pain",
            "Heart pounding",
            "Fast pulse",
            "Slow pulse",
            "Leg pain with exercise",
            "Leg swelling",
            "Joint pain",
            "Neck pain",
            "Joint swelling",
            "Joint stiffness",
            "Muscle aches",
            "Back pain",
            "Sores",
            "Rash",
            "Itching",
            "Change in a mole",
            "Unusual growth/spot"
          ]
        },
        {
          "type": "text",
          "name": "CurrentDate",
          "title": "Today's date:",
          "titleLocation": "left",
          "inputType": "date",
          "defaultValueExpression": "today()"
        }
      ]
    }
  ],
  "showTOC": true,
  "completeText": "Submit",
  "showPreviewBeforeComplete": true,
  "widthMode": "static",
  "width": "1200px"
};
```

### `src/App.vue`

```html
<template>
    <SurveyCreatorComponent :model="creator" />
</template>
<script setup lang="ts">
    import { SurveyCreatorModel } from "survey-creator-core";
    import { SurveyCreatorComponent } from "survey-creator-vue";
    import { Serializer } from "survey-core";
    import { formJSON } from "./survey_json";
    import "survey-core/survey.i18n";
    import "survey-creator-core/survey-creator-core.i18n";
    import "survey-core/survey-core.css";
    import "survey-creator-core/survey-creator-core.css";
    import "./index.css";
    import SurveyTheme from "survey-core/themes";
    import { registerCreatorTheme } from "survey-creator-core";

    registerCreatorTheme(SurveyTheme); // Add predefined Survey Creator UI themes

    // Add the `name` property to the survey and limit the length for question and column names
    Serializer.addProperty("survey", {
        name: "name",
        maxLength: 50,
        isRequired: true,
        category: "general",
        visibleIndex: 0
    });
    Serializer.findProperty("question", "name").maxLength = 50;
    Serializer.findProperty("matrixdropdown", "name").maxLength = 50;
    
    class TabServerCodeCreatorPlugin implements ICreatorPlugin {
        constructor(private creator: SurveyCreatorModel) {
            this.model = creator;
            creator.addTab({
                name: "servercode",
                plugin: this,
                title: "Domain Model Code",
                index: 0
            });
        }
        public activate(): void { }
        public deactivate(): boolean {
            return true;
        }
        public model: SurveyCreatorModel;
    }
    const creator = new SurveyCreatorModel();
    new TabServerCodeCreatorPlugin(creator);
    creator.JSON = formJSON;
</script>
```

### `src/index.css`

```css
.generatortextarea {
    width: 100%;
    height: 100%;
    padding: 7px;
}
```

### `src/main.ts`

```ts
import { createApp } from "vue";
import App from "./App.vue";
import ServerCode from "./ServerCode.vue";

const app = createApp(App);
app.component("svc-tab-servercode", ServerCode);
app.mount("#app");
```

### `src/shims-vue.d.ts`

```ts
/* eslint-disable */
declare module "*.vue" {
    import type { DefineComponent } from "vue"
    const component: DefineComponent<{}, {}, any>
    export default component
}
```

### `.eslintrc.js`

```js
module.exports = {
    root: true,
    env: {
        node: true
    },
    extends: [
        "plugin:vue/vue3-essential",
        "eslint:recommended",
        "@vue/typescript/recommended",
        "@vue/prettier",
        "@vue/prettier/@typescript-eslint"
    ],
    parserOptions: {
        ecmaVersion: 2020
    },
    rules: {
        "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
        "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off"
    },
    overrides: [
        {
            files: [
                "**/__tests__/*.{j,t}s?(x)",
                "**/tests/unit/**/*.spec.{j,t}s?(x)"
            ],
            env: {
                jest: true
            }
        }
    ]
};
```

### `babel.config.js`

```js
module.exports = {
  presets: ["@vue/cli-plugin-babel/preset"]
};
```

### `package.json`

```json
{
  "name": "surveyjs-library-vue3",
  "version": "0.1.0",
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "tslib": "2.6.1",
    "vue": "^3.4.1",
    "survey-core": "latest",
    "survey-vue3-ui": "latest",
    "survey-creator-core": "latest",
    "survey-creator-vue": "latest",
    "vue-router": "^4.0.0-0",
    "vuex": "^4.0.0-0"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^2.33.0",
    "@typescript-eslint/parser": "^2.33.0",
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-pwa": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-typescript": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "@vue/eslint-config-prettier": "^6.0.0",
    "@vue/eslint-config-typescript": "^5.0.2",
    "@vue/test-utils": "^2.0.0-0",
    "eslint": "^6.7.2",
    "eslint-plugin-prettier": "^3.1.3",
    "eslint-plugin-vue": "^7.0.0-0",
    "node-sass": "^4.12.0",
    "prettier": "^1.19.1",
    "sass-loader": "^8.0.2",
    "typescript": "~3.9.3"
  }
}
```

### `tsconfig.json`

```json
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}
```

## Other Frameworks

- [Angular](https://surveyjs.io/survey-creator/examples/create-domain-models/angular.md)
- [React](https://surveyjs.io/survey-creator/examples/create-domain-models/reactjs.md)
- [jQuery](https://surveyjs.io/survey-creator/examples/create-domain-models/jquery.md)
- [Vanilla JS](https://surveyjs.io/survey-creator/examples/create-domain-models/vanillajs.md)
