Modify New Question
Survey Creator raises an onQuestionAdded
event when users add questions to a survey. You can handle this event to modify the questions on the fly. In this demo, the onQuestionAdded
event is used to generate GUIDs and use them as question names.
Implementation
A function that handles the onQuestionAdded
event accepts an options
object as the second parameter. The object's question
property provides access to the question being added, while the reason
property contains a string value indicating how the question was added: dragged from the Toolbox ("DROPPED_FROM_TOOLBOX"
), created using the Add Question button ("ADDED_FROM_PAGEBUTTON"
), duplicated ("ELEMENT_COPIED"
), or converted from another question type ("ELEMENT_CONVERTED"
). In this demo, the onQuestionAdded
function changes the question's name
property to a GUID and title
property to a predefined value. These changes do not apply if the question is converted from another type, because in this case the question already has a GUID and a proper title.
var questionCounter = 1;
creator.onQuestionAdded.add((_, options) => {
if (options.reason === "ELEMENT_CONVERTED")
return;
const q = options.question;
q.name = guid();
q.title = "Question " + questionCounter;
questionCounter++;
});
To ensure that users don't change the generated GUIDs, make the name
property read-only using the Serializer
API:
import { Serializer } from "survey-core";
Serializer.findProperty("question", "name").readOnly = true;
Survey Creator uses question names in the UI. Now that the question names are GUIDs, they become hard to read and distinguish at a glance. To eliminate this disadvantage, enable the showObjectTitles
and showTitlesInExpressions
properties when you instantiate Survey Creator. With these settings, the Survey Creator UI will use question titles instead of the names.
const creatorOptions = {
// ...
showObjectTitles: true,
showTitlesInExpressions: true
}
Similar Events
In addition to onQuestionAdded
, Survey Creator raises other events that allow you to modify newly added survey elements dynamically. These events are handled similarly to onQuestionAdded
.
Event name | Raised when |
---|---|
onPanelAdded |
Raised when users add a panel to the survey. |
onPageAdded |
Raised when users add a page to the survey. |
onMatrixColumnAdded |
Raised when users add a column to a Multi-Select or Dynamic Matrix. |
onItemValueAdded |
Raised when users add a new item value (column, row, choice). |