Form.io Dynamic Translations
by brendanbond
HTML
<script src="https://cdn.form.io/formiojs/formio.form.min.js"></script>
<link rel="stylesheet" href="https://cdn.form.io/formiojs/formio.form.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<div class="btn-group" style="width:100%">
<button type="button" class="btn btn-success btn-group-item" onclick="setLanguage('sp')">Español</button>
<button type="button" class="btn btn-primary btn-group-item" onclick="setLanguage('en')">English</button>
<button type="button" class="btn btn-secondary btn-group-item" onclick="setLanguage('ch')">中文</button>
</div>
<div id="formio"></div>
JavaScript
Formio.createForm(document.getElementById('formio'), {
components: [
{
type: 'textfield',
key: 'firstName',
label: 'First Name',
placeholder: 'Enter your first name',
input: true
},
{
type: 'textfield',
key: 'lastName',
label: 'Last Name',
placeholder: 'Enter your last name',
input: true
},
{
type: 'survey',
key: 'questions',
label: 'Survey',
values: [
{
label: 'Great',
value: 'great'
},
{
label: 'Good',
value: 'good'
},
{
label: 'Poor',
value: 'poor'
}
],
questions: [
{
label: 'How would you rate the Form.io platform?',
value: 'howWouldYouRateTheFormIoPlatform'
},
{
label: 'How was Customer Support?',
value: 'howWasCustomerSupport'
},
{
label: 'Overall Experience?',
value: 'overallExperience'
}
]
},
{
type: 'button',
action: 'submit',
label: 'Submit',
theme: 'primary'
}
]
}, {
language: 'en',
}).then(function(form) {
var languages = {en: true};
window.setLanguage = function(lang) {
if (languages[lang]) {
return form.language = lang;
}
// Fetch the language from the Resource.
Formio.fetch('https://formiodata.form.io/language/submission?data.language=' + lang).then(function(resp) {
return resp.json();
}).then(function(result) {
languages[lang] = true;
form.addLanguage(lang, result[0].data.translations);
form.language = lang;
});
};
});