Using Google Translate in fields

From pmusers
Jump to: navigation, search

Google translation can be used to translate text in a DynaForm field. This example shows how to auto-translate from any language to English with translate.googleapis.com, using jQuery's .ajax() method.



DynaForm: Translate to English.json (right click and select Save link as)
Author: Amos Batto (amos@processmaker.com)
Version: 1.0 (2018-07-19)
Tested in: ProcessMaker 3.2.1 Community in Debian 8.4 with PHP 5.6.20 and Firefox 51



The following URL can used to translate text into many different languages:

https://translate.googleapis.com/translate_a/single?client=gtx&sl={source-lang}&tl={translation-lang}&dt=t&ie=UTF-8&q={text-to-translate}

Where:

  • {source-lang} can be auto or the ISO 639-1 code for the language.
  • {translation-lang} can be auto or the ISO 639-1 code for the language.
  • {text-to-translate} is the URL encoded text to be translated. This text can by encoded using JavaScript's encodeURI() function.

Note: Google has a monthly limit on the amount of text that can be translated for free using its API, so you may have to pay Google if planning to translate a large amount of text.


Create the following Dynaform:

translateToEnglishForm.png

This form has a "sourceLang" textarea where the user can enter text in any language and a "targetLang" textarea where the text will we translated into English. In addition, it has a "translateBtn" button which executes code to translate the text.

Then, add the following JavaScript to the DynaForm:

$("#translateBtn").find("button").click(function() {
  var sourceLang = 'auto';
  var targetLang = 'en';
  var textToTranslate = encodeURI( $("#sourceText").getValue() );
  var gUrl = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" 
           + sourceLang + "&tl=" + targetLang + "&dt=t&ie=UTF-8&q=" + textToTranslate;
  $.ajax({
    method: "GET",
    url: gUrl
  })
  .success(function( result ) {
    console.log(result);
    var trans = '';
    for (var i = 0; i < result[0].length; i++) {
      trans += result[0][i][0]; 
    }
    $("#targetText").setValue(trans);
    
  });
});

When the "translateBtn" button is clicked by the user, the click event handler first URL encodes the text in the "sourceText" textarea and places it inside a URL. Then, the .ajax() method is used to execute the URL and get an array from Google Translate. The code loops through the array and adds each sentence from the translation to the text which is placed in the "targetText" textarea.

UsingTranslationForm.png