LogoLogo
Getting StartedDevelopersDeployment GuideGet Help
  • Quick Links
  • Welcome to Form.io
    • Getting Started With Form.io
    • Launch a Form
    • Overview of Form.io
  • Developer Tool Ecosystem
    • PDF Solution
    • Enterprise Form Builder
    • Form View Pro
    • The Security Module
    • Accessibility Compliance Module
    • Developer License
    • SQL Connector - Deprecated
    • Integration Libraries
    • Form.io CLI Tool
  • User Guide
    • Introduction
    • Form.io Developer Portal
    • Teams
    • Projects
      • Project UI
      • Project Settings
      • Stages
      • Multi-Tenancy
    • Resources
      • ResourceJS
    • Forms
      • Form Creation
      • Form Types
      • PDF Forms
      • Embedding a Form
      • Form Revisions
      • Form Settings
    • Form Building
      • Form Builder UI
      • Form Components
        • Component Settings
        • Basic Components
          • Resource as Select Component Data Source
        • Advanced Components
        • Layout Components
        • Data Components
        • Premium Components
          • Nested Forms
        • Custom Components
      • Logic & Conditions
      • Existing Resource Fields
      • Actions
    • Submissions
      • Accessing Submissions
      • Importing Submissions
    • Form.io eSignature - Coming Soon
    • Form.io Reporting Module
    • PDF Template Designer
    • Form View Pro
    • Form Manager
    • Enterprise Form Builder Module
      • Installation
      • User Guide
  • Developer Guide
    • Introduction
      • Application Development
      • API Documentation
    • Form Development
      • Form Renderer
      • Form Builder
      • Form Embedding
      • Form Evaluations
      • Form Templates
      • Custom Components
      • Translations
    • JavaScript Development
      • JavaScript SDK
      • JavaScript Frameworks
      • JavaScript Utilities
    • Authentication and Authorization
      • SAML
      • OAuth
      • LDAP
      • Resource Based Authentication
      • Email Authentication
      • Two-Factor Authentication
    • Roles and Permissions
      • Field Match-Based Access
      • Field-Based Resource Access
      • Group Permissions
    • Integrations
      • Email Integrations
      • File Storage
      • Google Developer Console
      • eSign Integrations
      • Relational Databases
    • Modules
    • Fetch Plugin API
    • CSS Frameworks
    • Offline Mode
    • Audit Logging
  • Deployments
    • Self-Hosted Deployment
      • Local Deployment
        • Local File Storage
      • Kubernetes
      • Cloud Deployment
        • AWS Deployment
          • AWS Lambda
          • Form.io/AWS Elastic Beanstalk End-To-End Encrypted Deployment
        • Azure Deployment
          • Azure App Service
            • Azure MSSQL Connector - Deprecated
          • Azure Virtual Machine
          • Azure Kubernetes Service
          • Set up the DB
        • GCP Deployment
          • GCP Cloud Run
      • On-Premise Deployment
      • Enterprise Server
      • PDF Server
    • Deployment Configurations
      • DNS Configuration
      • Load Balancer Configuration
    • Licenses
      • License Management
      • Library Licenses
    • Portal Base Project
      • Portal SSO
      • Portal Translations
    • Maintenance and Migration
      • Changes to Premium Libraries
  • FAQ
    • FAQ
    • Tutorials & Workflows
      • Password Reset
      • Dynamic Select Filtering
      • Approval Workflow
      • SSO Email Token
      • Embedding A Video
      • Data Source Validation
      • Select Data Source Options
      • Nested Form Workflows
        • Nested Wizard Forms
      • Save as Draft
      • Role-Based Conditions
      • Custom Component
      • Dynamic Radio and Select Box Values
      • Override CKEDITOR
    • Errors
    • Examples
    • License Utilization Checks
  • Contact Us
Powered by GitBook
On this page
  • Introduction
  • Rendering Translations
  • Dynamic Translations using Resources
  • Create a Language Resource
  • Dynamic Language Controller
  • Custom Error Translation

Was this helpful?

  1. Developer Guide
  2. Form Development

Translations

Documentation of Form.io Translations

PreviousCustom ComponentsNextJavaScript Development

Last updated 2 months ago

Was this helpful?

Introduction

The Form.io Platform uses the system as the mechanism for displaying all of the translations within the JavaScript Renderer and Builder. Refer to the i18Next documentation to understand all of the mechanisms that are available to handle translations within an application and forms rendered by Form.io. The Form.io Renderer exposes the i18next platform within thei18next variable in the renderer, and all options for this library can be introduced through the i18n configuration variable.

The following example illustrates how the i18next framework can be initialized and accessed within the Form.io renderer:

Formio.createForm(document.getElementById('formio'), 'https://examples.form.io/example', {
    i18n: {...} // These options are passed to the i18Next framework
}).then((form) => {
    console.log(form.i18next); // Exposes the i18Next framework instance.
    
    form.language = 'es'; // Changes the language of the i18Next framework.
});

Following initialization, the features documented for the apply. The following topics provide additional guidance on rendering a form with internationalization:

Rendering Translations

In order to provide translations to the renderer, introduce these translations using i18n configurations. There are also a few methods within the Form.io Renderer that can be used to change the language dynamically. For example, the following HTML code introduces buttons within the application that will trigger a language change:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css">
<script src="https://cdn.form.io/js/formio.embed.js"></script>

<div class="btn-group">
  <button type="button" class="btn btn-primary" onclick="setLanguage('sp')">Español</button>
  <button type="button" class="btn btn-secondary" onclick="setLanguage('en')">English</button>
  <button type="button" class="btn btn-info" onclick="setLanguage('ch')">中文</button>
  <button type="button" class="btn btn-success" onclick="setLanguage('ar')">العربية</button>
</div>

<div id="formio"></div>

After this, provide the following code to define the form, provide the translated text, and then dynamically change the text when the buttons have been clicked. The code will look as follows:

Formio.createForm(document.getElementById('formio'), {
    components: [
      {
        type: 'textfield',
        key: 'firstName',
        label: 'First Name',
        tooltip: "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',
    i18n: {
      sp: {
        'First Name': 'Nombre de pila',
        'Name': 'Nombre',
        'Last Name': 'Apellido',
        'Enter your first name': 'Ponga su primer nombre',
        'Enter your last name': 'Introduce tu apellido',
        'How would you rate the Form.io platform?': '¿Cómo calificaría la plataforma Form.io?',
        'How was Customer Support?': '¿Cómo fue el servicio de atención al cliente?',
        'Overall Experience?': '¿Experiencia general?',
        Survey: 'Encuesta',
        Excellent: 'Excelente',
        Great: 'Estupendo',
        Good: 'Bueno',
        Average: 'Promedio',
        Poor: 'Pobre',
        'Submit': 'Enviar',
        complete: 'Presentación Completa'
      },
      ch: {
        'First Name': '名字',
        'Last Name': '姓',
        'Enter your first name': '输入你的名字',
        'Enter your last name': '输入你的姓氏',
        'How would you rate the Form.io platform?': '你如何评价Form.io平台?',
        'How was Customer Support?': '客户支持如何?',
        'Overall Experience?': '总体体验?',
        Survey: '调查',
        Excellent: '优秀',
        Great: '大',
        Good: '好',
        Average: '平均',
        Poor: '错',
        'Submit': '提交',
        complete: '提交完成'
      },
      ar: {
        'First Name': 'الاسم الأول',
        'Last Name': 'اسم العائلة',
        'Enter your first name': 'أدخل اسمك الأول',
        'Enter your last name': 'أدخل اسم عائلتك',
        'How would you rate the Form.io platform?': 'كيف تقيم منصة Form.io؟',
        'How was Customer Support?': 'كيف كان دعم العملاء؟',
        'Overall Experience?': 'التجربة العامة؟',
        Survey: 'استبيان',
        Excellent: 'ممتاز',
        Great: 'رائع',
        Good: 'جيد',
        Average: 'متوسط',
        Poor: 'ضعيف',
        'Submit': 'إرسال',
        complete: 'تم الإرسال'
      }
    }
  }).then(function(form) {
    window.setLanguage = function(lang) {
      form.language = lang;
      document.body.setAttribute("dir", lang === "ar" ? "rtl" : "ltr"); // Switch direction
    };
  });

Right-to-left language support

In the above example, note the setAttribute() element used to accommodate languages rendered in a right-to-left direction. Include any additional language codes that may need to be rendered this way.

This code within a JSFiddle will work as follows:

Dynamic Translations using Resources

The above example s not dynamic and requires an application change in order to introduce new translations. Make the translations dynamic using Form.io Resources so that any non-developer can contribute to the translation process. This can be achieved using the following method:

Create a Language Resource

The first step is to create a Language resource within your Project, called Language. Within this resource, add the following fields:

  • A Select Field for the Language Code. For the Data Source, use Values, and provide the language as the Label. Then, add the lang-code as the value as seen:

  • A Data Map component, which contains a Translation Text Field like the following:

The completed resource will look like the following:

Now press Create Resource button to create the new Resource.

Once this is created, use the resource to create a new submission for each translation. The following example illustrates the fields for Español:

Create the submission to add the "language". This will be used to manage all of the translations in a standard way. Input the rest of the language translations the same way until there are multiple to choose from.

Language Resource "Read All Submissions" Access

For most applications, the end user will be authenticated when they are switching between languages. In some cases, the user may be anonymous. As with any resource, ensure that the proper Role has access to the Read All Submissions permission within the Access section of the Language form.

Dynamic Language Controller

Now that there is a language resource with the correct access, write the logic that will perform the dynamic language display. The form controller that establishes a dynamic language is pretty simple. It will send an API call to the form resource submission API (where the user should have "read all" submission access) to fetch the Submission that is associated with the language that was chosen. Implement some in-memory cache to reduce re-fetching the submissions as the user clicks between different languages. Put most of the logic within the window.setLanguage method used above. Here is what the Form Controller should look like:

var languages = {en: true};
window.setLanguage = function(lang) {
  // If we already have loaded the language, then just set it with the sdk.
  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) {
    // Ensure future sets will use the cached language.
  	languages[lang] = true;
  
    // Add this language.
    form.addLanguage(lang, result[0].data.translations);
    
    // Set this language.
    form.language = lang;
  });
};

Here is a JSFiddle demonstrating this dynamic loading system working:

Custom Error Translation

Different error messages may be used based on what the current language is. You can achieve this by setting the i18n translations in the application. Below is an example of how to add translations to custom error messages

  1. Start by creating a new form.

  2. Add a Text Field to the form.

  3. Open Settings > Validation > Custom Validation add the following code:

valid = input === 'example' ? true : 'mycustomerror';

  1. In the application, create the form above and add translations for the error message. The code should look something like the following:

Formio.createForm(document.getElementById('formio'), {
                components: [
                    {
                        "label": "Text Field",
                        "applyMaskOn": "change",
                        "tableView": true,
                        "validate": {
                            "custom": "valid = input === 'example' ? true : 'mycustomerror';"
                        },
                        "validateWhenHidden": false,
                        "key": "textField",
                        "type": "textfield",
                        "input": true
                    }
                ]
            }, {
                language: 'sp',
                i18n: {
                    en: {
                        "mycustomerror": 'Your name must be example'
                    },
                    sp: {
                        "mycustomerror": 'Tu nombre debe ser ejemplo.'
                    }
                }
            })

At this point, error message language will be set based on what the current language is.

To interpolate data from the form, use the {{}} notation. For example, to interpolate the current input being typed in, change 'Your name must be example' to 'Your name can't be {{data.textField}}'

i18Next
i18Next framework