i18n

i18n

Andreas S.Andreas S. Posts: 208Questions: 74Answers: 4

How can the user switch between two languages? I have two languages, and one should the user selected. I my case it is German and English. Default should be English. How can I configure that the editor or the Datatable to load the correct language file?

And is it possible to add in the lang file my own var to show the editor label in the correct language?
for example the length of a pool, en: pool length, de: Beckenlänge.

Andreas

Answers

  • rf1234rf1234 Posts: 2,991Questions: 87Answers: 421
    edited May 2017

    "How can the user switch between two languages?"
    Well, that should be done outside Data Tables I guess. You could take the browser language as the default. If the browser language is German you take German, else you take English. And then you could have a button the user could click on to choose manually. You could save the language in a cookie.
    This is what I do on the server side in PHP:

    //at this point it is sufficient to check server language and the cookie
    //language changes can only be made after page load and will cause a 
    //refresh which will be recognized through the cookie set by javascript upon
    //change of language
    
    if (isset($_COOKIE['lang'])) {
        $language = filter_input(INPUT_COOKIE, 'lang', FILTER_SANITIZE_STRING);
    } else {
        $language = filter_var(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2), FILTER_SANITIZE_STRING);
    }
    if ($language != "de") {
        $language = "en";
    }
    //set session variable
    $_SESSION['lang'] = $language;
    

    Javascript; I use a button called "languagepicker" ... and a javascript plugin called cookies to read and write cookies. The Ajax call only returns the result of this:
    filter_var(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2), FILTER_SANITIZE_STRING)

    function languageSelection() {
        if (!Cookies.get('lang')) {
            //get the server language if no cookie
            $.ajax({
                type: "POST",
                url: 'actions.php?action=languageSelection',
                //subsequent code may not run before completion
                async: false,
                dataType: "json",
                success: function (data) {
                    lang = data.lg;      
                }
            });
            //if server language is not German it will be set to English
            if (lang != "de") {
                lang = "en";
            }
            Cookies.set('lang', lang, {expires: 360});
        } else {
            lang = Cookies.get('lang');
        }
        $('#languagepicker').on('change', function(){
           .....
           ......
            Cookies.set('lang', lang, {expires: 360});
            location.reload(true);
        });
    }
    

    After implementing the language selection in any fashion you like you can set the language settings for Editor and Data Tables like this:

    //Editor default settings!
    if (lang === 'de') {
        $.extend( true, $.fn.dataTable.Editor.defaults, {            
            i18n: {
                remove: {
                    button: "Löschen",
                    title:  "Eintrag löschen",
                    submit: "Endgültig Löschen",
                    confirm: {
                        _: 'Sind Sie sicher, dass Sie die %d ausgwählten Zeilen löschen wollen?',
                        1: 'Sind Sie sicher, dass Sie die ausgewählte Zeile löschen wollen?'
                    }
                },
                edit: {
                    button: "Bearbeiten",
                    title:  "Eintrag bearbeiten",
                    submit: "Änderungen speichern"
                },
                create: {
                    button: "Neuer Eintrag",
                    title:  "Neuen Eintrag anlegen",
                    submit: "Neuen Eintrag speichern"
                },
                datetime: {
                        previous: 'Zurück',
                        next:     'Weiter',
                        months:   [ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ],
                        weekdays: [ 'So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa' ],
                        amPm:     [ 'am', 'pm' ],
                        unknown:  '-'
                },
                error: {            
                        system: "Ein Systemfehler ist aufgetreten (<a target=\"_blank\" href=\"//datatables.net/tn/12\">Für mehr Informationen</a>)."
                },
                multi: {
                        title: "Mehrere Werte",         
                        info: "Die ausgewählten Elemente enthalten verschiedene Werte für das Feld. Um alle Elemente für diess Feld auf den gleichen Wert zu setzen, klicken Sie bitte hier. Ansonsten werden die Elemente ihren jeweiligen Wert behalten.",
                        restore: "Änderungen rückgängig machen",
                        noMulti: "Dieses Feld kann einzeln bearbeitet werden, aber nicht als Teil einer Gruppe."
                },
            }      
        });
    }
    
    //Data tables language settings
    if (lang === 'de') {
        $.extend( true, $.fn.dataTable.defaults, {
            "language": {
                "decimal": ",",
                "thousands": ".",
                "info": "Anzeige _START_ bis _END_ von _TOTAL_ Einträgen",
                "infoEmpty": "Keine Einträge",
                "infoPostFix": "",
                "infoFiltered": "(gefiltert aus insgesamt _MAX_ Einträgen)",
                "loadingRecords": "Bitte warten Sie - Daten werden geladen ...",
                "lengthMenu": "Anzeigen von _MENU_ Einträgen",
                "paginate": {
                    "first": "Erste",
                    "last": "Letzte",
                    "next": "Nächste",
                    "previous": "Zurück"
                },
                "processing": "Verarbeitung läuft ...",
                "search": "Suche:",
                "searchPlaceholder": "Suchbegriff",
                "zeroRecords": "Keine Daten! Bitte ändern Sie Ihren Suchbegriff.",
                "emptyTable": "Keine Daten vorhanden",
                "aria": {
                    "sortAscending":  ": aktivieren, um Spalte aufsteigend zu sortieren",
                    "sortDescending": ": aktivieren, um Spalte absteigend zu sortieren"
                },
                //only works for built-in buttons, not for custom buttons
                "buttons": {
                    "create": "Neu",
                    "edit": "Ändern",
                    "remove": "Löschen",
                    "copy": "Kopieren",
                    "csv": "CSV-Datei",
                    "excel": "Excel-Tabelle",
                    "pdf": "PDF-Dokument",
                    "print": "Drucken",
                    "colvis": "Spalten Auswahl",
                    "collection": "Auswahl",
                    "upload": "Datei auswählen...."
                },
                "select": {
                    "rows": {
                        _: '%d Zeilen ausgewählt',
                        0: 'Zeile anklicken um auszuwählen',
                        1: 'Eine Zeile ausgewählt'
                    }
                }
            }            
        } );        
    } else {
        $.extend( true, $.fn.dataTable.defaults, {
            "language": {
                "select": {
                    "rows": {
                        _: '%d rows selected',
                        0: 'Click row to select',
                        1: '1 row selected'
                    }
                }
            }
        } );
    }
    
    
    
  • rf1234rf1234 Posts: 2,991Questions: 87Answers: 421

    And this is to set the editor labels:
    https://editor.datatables.net/reference/api/field().label()

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Just to quickly add to @rf1234's excellent answer - there is no API in DataTables to dynamically change the language strings that it uses. They have to be set when the table is initialised (usually at page load time).

    Allan

  • rf1234rf1234 Posts: 2,991Questions: 87Answers: 421

    good to know, Allan. And also no problem because of the page refresh upon language change. I still have to translate all the Editor field labels myself too ...

    I've just tested this and it worked. ("lang" is a global variable)

    var contractCredEditor = new $.fn.dataTable.Editor( {
        ajax: {
            url: 'actions.php?action=tblContractCred'
        },
        table: "#tblContractCred",
        fields: [ {
            label: "For:",
            name:  "contract.govdept_id", //render gov_name, govdept_name
            type: "selectize", 
            opts: {
                create: false,
                maxItems: 1,
                maxOptions: 15,
                openOnFocus: false,
                allowEmptyOption: false,
                placeholder: "Please select a Department"
                }
            }
        ]        
    } );
    
    contractCredEditor    
        .on('open', function(e, mode, action) {            $
            if (lang === 'de') {
                contractCredEditor.field( 'contract.govdept_id' ).label( 'Für:' );
            }    
        });
    

    Viel Erfolg und schöne Grüße nach Deutschland / Österreich / Schweiz, Andreas!

    Roland

  • rf1234rf1234 Posts: 2,991Questions: 87Answers: 421
    edited May 2017

    I also tried to get the placeholder "Please select a Department" bilingual.
    editor.field().opts({placeholder: ....}) didn't work.

    So I tried this approach which will also work for everything else in Editor and Data Tables:

    var placeholder;
    var label;
    if (lang === 'de') {
        placeholder = 'Bitte wählen Sie eine Abteilung';
        label = 'Für:';
    } else {
        placeholder = 'Please select a Department';
        label = 'For:';
    }
    
    var contractCredEditor = new $.fn.dataTable.Editor( {
        ajax: {
            url: 'actions.php?action=tblContractCred'
        },
        table: "#tblContractCred",
        fields: [ {
            label: label,
            name:  "contract.govdept_id", //render gov_name, govdept_name
            type: "selectize",
            opts: {
                create: false,
                maxItems: 1,
                maxOptions: 15,
                openOnFocus: false,
                allowEmptyOption: false,
                placeholder: placeholder
                }
            }
        ]       
    } );
    
  • Andreas S.Andreas S. Posts: 208Questions: 74Answers: 4

    Thanks for your answers. I will try it soon.

    Andreas

This discussion has been closed.