Question T8689
Visible to All Users

Change question type at runtime?

created 3 years ago

Is there a way to change the question type at runtime? For example on a title action of a question.

I looked in the API docs but couldn't find relevant props for Question. I also cound't find add / replace Question like methods on Survey.
Simply calling question.setPropertyValue('type', 'radiogroup' ) or question..type = 'radiogroup' doesn't do anything.
ifFit is only called once.
I assume there is no simple way to have a custom component adapt to the type using the existing core Survey question widgets? So we'd always use a custom component, but when the question type is "text" it will use Survey.js regular text component inside the custom component? I feel like it might be possible by creating a sub Survey.js instance, but that seems like a performance nightmare.

Maybe we'd need to make a custom Panel like component? Which could then wrap one or more regular questions. But that might just move the issue as I'm not sure there is a way to change the contents of a Panel like component easily.

Context:
We have a large complicated survey where vendors fill in information for multiple products. Some questions will be generally applicable, but some need to be answered per product. Which depends on the vendor. We'd love to add a "Per product" checkbox to each question (as title action). Checking it should then replace the question for a custom component, where we re-use all the question info to ask the questions per product.

(We have figured out the title actions and custom component bit)

Current prototype: https://stackblitz.com/edit/vite-vue2-wjkj4-tekrte?file=src%2FperProduct.js

Answers approved by surveyjs Support

created 3 years ago

Hello Peter,
You can create a new question based on existing one and delete the old question.
Here is the example of changing radiogroup to checkbox and vise versa:

JavaScript
function changeQuestionType({     const oldQuestion = survey.getQuestionByName("car");     index = oldQuestion.parent.elements.indexOf(oldQuestion);     let newtype = oldQuestion.getType() === "checkbox" ? "radiogroup""checkbox";     const newQuestion = Survey.Serializer.createClass(newtype);     newQuestion.fromJSON(oldQuestion.toJSON());     oldQuestion.parent.addQuestion(newQuestion, index);     oldQuestion.delete(); }

Thank you,
Andrew
SurveyJS Team

    Comments (2)

      You guys are amazing, thanks for the quick response as always.

      I just found the addQuestion method in the docs:
      https://surveyjs.io/Documentation/Library?id=PanelModelBase#addQuestion

        You are welcome!

        Andrew
        SurveyJS Team