Skip to content

Translations

James R. Maxfield edited this page Mar 16, 2018 · 12 revisions

Formio.js uses i18n, a lightweight translation module, to allow users add and manipulate a forms language output. To learn more about accomplish using just formio.js check out those docs here. This example goes one step further, leveraging in form event listeners to change form elements via inside an Angular 2+ application.

Project Context

To get underway either launch an existing Angular 2+ application or create a new project by following Angular's getting started guide. The angular-formio wiki home shows how to properly import the FormioModule into the app.module.ts which is needed to gain access to and render formio.js.

example.component.ts

import { Component, OnInit } from '@angular/core';
import { createForm } from 'formiojs';

@Component({
  selector: 'app-index',
  template: <div id="formio"></div>'
})

export class IndexComponent implements OnInit {
  formURL: string;
  
  constructor() {
    this.formURL = 'https://wzddkgsfhfvtlmv.form.io/translations';
  }

ngOnInit() {
    createForm(document.getElementById('formio'), this.formURL, {
      language: 'en',  i18n: { 'en': { Submit: 'Complete' } }
    }).then(function(form) {
      form.i18next.options.resources.es = {
        translation : {
          'Submit' : 'Enviar',
          'Language' : 'Idioma',
          'Your Name' : 'Tu nombre',
          'Translations' : 'Traducciones',
          'Must Match Other Field' : 'Debe coincidir con otro campo',
          'Unique Email Address' : 'Dirección de correo electrónico única',
          'Please correct all errors before submitting.' : 'Por favor, corrija todos los errores antes de enviar.',
          'Matching Text Field' : 'Campo de texto coincidente',
          'Confirm Text Field' : 'Confirmar campo de texto',
          required : '{{field}} es requerido.',
          invalid_email: '{{field}} debe ser un correo electrónico válido.',
          error : 'Por favor, corrija los siguientes errores antes de enviar.'
        }
      };

      form.on('makeEnglish', function () {
        form.language = 'en';
        form.redraw();
      });

      form.on('makeSpanish', function () {
        form.language = 'es';
        form.redraw();
      });
    });
  }
}

Alternatively, users can set the language based on the operator’s browser settings.

form.language = window.navigator.language.substring(0, 2);

Form Defaults

Here is a list of some helpful defaults:

{
  error : "Please fix the following errors before submitting.",
  invalid_date :"{{field}} is not a valid date."
  invalid_email : "{{field}} must be a valid email."
  invalid_regex : "{{field}} does not match the pattern {{regex}}."
  mask : "{{field}} does not match the mask."
  max : "{{field}} cannot be greater than {{max}}."
  maxLength : "{{field}} must be shorter than {{length}} characters."
  min : "{{field}} cannot be less than {{min}}."
  minLength : "{{field}} must be longer than {{length}} characters."
  next : "Next"
  pattern : "{{field}} does not match the pattern {{pattern}}"
  previous : "Previous"
  required : "{{field}} is required"
}

Manual Definition

Feel free to replace the this.formURL with a component object

{
  components: [
    {
      key: "panel2",
      title: "Language",
      theme: "default",
      components: [
        {
          key: "panel2Table",
          numRows: 1,
          numCols: 2,
          rows: [
            [
              {
                components: [
                  {
                    input: true,
                    label: "English",
                    key: "panel2TableEnglish",
                    size: "md",
                    action: "event",
                    theme: "primary",
                    type: "button",
                    event: "makeEnglish"
                  }
                ]
              },
              {
                components: [
                  {
                    input: true,
                    label: "Spanish",
                    key: "panel2TableSpanish",
                    size: "md",
                    action: "event",
                    theme: "primary",
                    type: "button",
                    event: "makeSpanish"
                  }
                ]
              }
            ]
          ],
          type: "table",
          label: "panel2Table",
          customClass: "custom-table"
        }
      ],
      type: "panel",
      breadcrumb: "default",
      label: "panel2"
    },
    {
      key: "panel",
      title: "Translations",
      theme: "default",
      components: [
        {
          input: true,
          label: "Your Name",
          key: "yourName",
          validate: {
            required: true
          },
          type: "textfield"
        },
        {
          input: true,
          inputType: "email",
          label: "Unique Email Address",
          key: "uniqueEmailAddress",
          unique: true,
          type: "email",
          validate: {
            required: true
          }
        },
        {
          label: "Columns",
          key: "columns",
          columns: [
            {
              components: [
                {
                  autofocus: false,
                  input: true,
                  tableView: true,
                  inputType: "text",
                  label: "Matching Text Field",
                  key: "matchingTextField",
                  validate: {
                    required: true
                  },
                  type: "textfield"
                }
              ],
              width: 6
            },
            {
              components: [
                {
                  input: true,
                  inputType: "text",
                  label: "Confirm Text Field",
                  key: "confirmTextField",
                  validate: {
                    required: true,
                    custom: "valid = (input === data.matchingTextField) ? true : 'Must Match Other Field';"
                  },
                  type: "textfield",
                  labelPosition: "top",
                  customError: "Unexpected end of input"
                }
              ],
              width: 6
            }
          ],
          type: "columns"
        }
      ],
      type: "panel"
    },
    {
      input: true,
      label: "Submit",
      key: "submit",
      action: "submit",
      theme: "primary",
      type: "button"
    }
  ]
}