How to translate webform messages?

Hi, would like to show messages depending on language https://getkirby.com/docs/cookbook/forms/basic-contact-form#the-contact-form-controller

  $messages = [
        'name'  => 'Please enter a valid name',
        'email' => 'Please enter a valid email address',
        'text'  => 'Please enter a text between 3 and 3000 characters'
    ];

How can I translate “Please enter a valid name” and similar?

In a multi-language site, you can use the translations array in your language definition file to set translations:

`/site/languages/en.php

<?php

return [
    'code'      => 'en',
    'default'   => true,
    'direction' => 'ltr',
    'locale'.   => [
        'en_US'
    ],
    'name' => 'English',
    'translations' => [
        'name'  => 'Please enter a valid name',
        'email' => 'Please enter a valid email address',
        'text'  => 'Please enter a text between 3 and 3000 characters'

    ],
    'url' => '/'
];

And so on for each language…

You can then use the t() helper to fetch these translations:

 $messages = [
    'name'  => t('name'),
    'email' => t('email'),
    'text'  => t('text')
];
1 Like

Thank you, wasn’t sure about syntax here: ‘Please enter a valid name’, that it should be just t(‘name’) without anything else. Checked, all works fine. Only should be commas at the end of lines, right?

 $messages = [
    'name'  => t('name'),
    'email' => t('email'),
    'text'  => t('text')
];

Yes, of course.

You can set a fallback in case a message is not defined:

 'name'  => t('name', 'The name field is required"),
1 Like