Jump to content

field label language problem


Recommended Posts

I've spent few hours at this problem, but still can't solve it -

// this code works not as expected - outputs only in default language, even if $user->language is different.
echo $user->fields->get("some_text_field")->label;

// while this code in the same php file works as expected - output follows $user->language
echo $page->any_field; 

Note: some_text_field field label is a multi-language field, all translations available.

If I try to do something like this:

echo $user->fields->get("some_text_field")->label->getLanguageValue($user->language);

it returns:

Error: Call to a member function getLanguageValue() on a non-object

Please, help - I want to output field label in current language! )) Thanks!

Link to comment
Share on other sites

Meanwhile, discovered why

echo $user->fields->get("some_text_field")->label->getLanguageValue($user->language)  

doesn't work. It is because $user->fields->get("some_text_field")->label returns string. Yes, I'm newbie )))

Still trying to find access to another translation in my field's label field... w/o success after another portion of experiments... 

Link to comment
Share on other sites

Hi valan,

I've found a solution. The translations of the labels (not default) are stored in the 'data' field in the 'fields' table, as JSON.

Example: {"label1012":"Weight"} where 1012 is the ID of the language.

You can try this code:

$label = 'label';
if ($user->language->name != 'default') {
  $label = "label{$user->language}";

// Output label in correct language
echo $user->fields->get('field')->$label;
  • Like 5
Link to comment
Share on other sites

WOW!!! It works!

Wanze, thank you for help! - I've started to think that problem doesn't have elegant solutions in PW. But you proved that PW has such solution! 

P.S. hope to see this kind of hints documented sometime by core PW team!

  • Like 2
Link to comment
Share on other sites

$label = 'label';
if ($user->language->title != 'no') {
$label = "label{$user->language}";

echo $page->fields->get('phone')->$label;

The above code works great on a regular php page, but I can´t get it to work inside a function - yes, yes - newbie :-)

function renderAuthorData($page) {

	$na = "<span class='na'>n/a</span>";
	$download = $page->files->first()->name;
	//Check if author is an employee
	$vista = $page->vista;
	if($vista == 1){
	$label = 'label';
	if ($user->language->title != 'no') {
	$label = "label{$user->language}";
	$out =	"\n<table class='publication_data'>" .
		//Check if author has a specific function
		$out .= "\n\t<tr><th>". ($page->fields->get('function')->$label) ."</th><td>". ($page->function ? $page->function : $na) . "</td></tr>";
		$out .= "\n\t<tr><th>". ($page->fields->get('author_title')->$label) ."</th><td>" . ($page->author_title ? : $na) . "</td></tr>" .
				"\n\t<tr><th>". ($page->fields->get('phone')->$label) ."</th><td>" . ($page->phone ? : $na) . "</td></tr>" .
				"\n\t<tr><th>". ($page->fields->get('author_email')->$label) ."</th><td>" . ($page->author_email ? : $na) . "</td></tr>" .
				"\n\t<tr><th>". ($page->fields->get('address')->$label) ."</th><td>" . ($page->address ? : $na) . "</td></tr>" .
				"\n\t<tr><th>CV</th><td><a href='{$page->files->first()->url}'>" . $download . "</a> ({$page->files->first()->filesizeStr})</td></tr>" .
				"\n\t</tbody>" .
	}else if($vista == 0){
	$out =	"\n\t<div style='clear:both;'><p>{$page->title} er ikke ansatt i Vista Analyse AS, men er medforfatter på følgende publikasjon(er):</p></div>";
	return $out;


It would be great to check for $user->language from inside a function. Can anyone help me with this? Probably very easy for someone with more PHP knowledge than me....

(The slightly modified code is from Ryan´s Skyscraper Profile - I have spent a few hours "dissecting" that profile to make a site for client - will share next week in the forum)

Link to comment
Share on other sites

Hi Peter,

That's because all the API variables like $users, $page, $pages... are not known to the function. PHP - scope problem.

The solution is to use the global wire() function from Pw to get the API variables:

$vista = wire('page')->vista;
// ...
if (wire('user')->language->title != 'no')) {
// ...
  • Like 3
Link to comment
Share on other sites

Thanks Wanze,

I got the if statement to work, but not the rest...

$label = 'label';
if (wire('user')->language->title != 'no'){ //Works
$label = "label{wire('user')->language}"; //Doesn't work

Probably just a matter of correcting my syntax :-)


Link to comment
Share on other sites

  • 2 months later...

I have problems rendering the correct field label for anything other than the default langauge.  (this in the template / frontend, not admin)

I'm using PW 2.3.2 dev version, and the values all output fine. It's just that the field labels only show the default language label text, nothing else.

Is there a special syntax I have to use? Or do I still have to manually check for $user->language somehow to get this done? I was under the impression it wouldn't be necessary anymore with 2.3.2. With 4 languages and approx. 50 custom fields, I'd really like to streamline things a bit (all field labels are correctly setup in each language). Or is that something that will be ready only with 2.4?

Link to comment
Share on other sites

I have a hard time to understand why one need the field labels (in different languages) in the front-end. After all if the it should render the language the user currently is viewing.

We covered this already in another thread and there's the solution above and I don't think there's something like you mention on the plan but maybe I miss something. But it would be easy to build a function or module to help out but there's barely anything needed to get a translated label.

$body = $fields->get("body");
$lang = $languages->get("de");
echo $body->get("label$lang"); // german label
Link to comment
Share on other sites

Thanks. I'll try that tomorrow morning.

The reason I need it in the frontend is simple: The various fields generate product specifications in the frontend, as lists or tables. Having to hardcode the field-labels for each addtl. language in the template, when it is already defined in the backend, seems unneccessary, tedious duplicate work. Most values are numeric, but the titles (labels) are always strings. I don't think it's that much of a rare / exotic situation.

After all, an english speaking visitor wants to see "weight", not "Gewicht". A French guy expects "poids", etc.

I have a hard time to understand why one need the field labels (in different languages) in the front-end. 

  • Like 1
Link to comment
Share on other sites

I understand and know this, but why do you need to get the translation when it is just already there. It will output in the language the user views the page ($user->language)

This works just fine in the language the user view the page.

echo $fields->get("body")->label;

Edit: ah, hm it does not? :)

Ok it doesn't get translated as with page fields. Since it's meant to be used for backend context there's no language value for fields settings.

So you either use a $lang variable like this:

$lang = $user->language->isDefault() ? "" : $user->language->id; // Default needs no id
echo $fields->get("body")->get("label$lang");

Or a little hook to add method to the $fields template API var. :)

// from template or a autoload module
$fields->addHook("getLabel", null, "getLabelLang");
function getLabelLang($event){
    $field = $event->arguments(0);
    $lang = wire("user")->language->isDefault() ? "" : wire("user")->language->id;
    $event->return = wire("fields")->get($field)->get("label$lang");

// now we use it and it will recognize user lang
echo $fields->getLabel("body");
  • Like 10
Link to comment
Share on other sites

Hooray! Thank you. I'm using your hook now in an include, and it works wonderfully.

Guess I'll have to get acquainted with hooks sooner or later...

Do you think this is worth suggesting in the Wishlist + Roadmap forum?

Link to comment
Share on other sites

I have a hard time to understand why one need the field labels (in different languages) in the front-end. After all if the it should render the language the user currently is viewing.

For me, it is because I have a hidden "about" section in my page. I have an about_title and about_description field, but to get to open this hidden "about" section, I have a button labeled "about"/"(about in chinese)". I don't want to have to create whole 'nother field just for "about_button". This is why I wanted to just use the label name for my field, which I already have translated.  I searched and found this thread extremely helpful ^^

I am so glad that this thread popped up just as I encountered the same problem. You guys are awesome  :lol: 

Link to comment
Share on other sites

  • 2 years later...

Dear all,

I know this post is old, but in case someone else stumbles across it, here is a modified version of Soma's getLabel() hook which takes an optional second parameter to decide if you want a fallback to the default language if no localized name of that field is available:

$fields->addHook("getLabel", null, "getLabelLang");
function getLabelLang($event){
    $field = $event->arguments(0);
    $fallback = $event->arguments(1) === null ? true : $event->arguments(1);
    $lang = wire("user")->language->isDefault() ? "" : wire("user")->language->id;
    $field = wire("fields")->get($field);
    $caption = $field->get("label$lang");
    $caption = (count($caption) === 0 && $fallback) ?  $field->get("label") : $caption;
    $event->return = $caption;



-> returns the localized label name with fallback to default language.

$fields->getLabel("labelName", false);

-> returns the label name without fallback to default language.

I am not very good with php, any code improvements welcome!  :)

  • Like 3
Link to comment
Share on other sites

  • 9 months later...
  • 2 months later...
On 16. November 2015 at 5:36 AM, lenno said:

I know this post is old, but in case someone else stumbles across it, here is a modified version of Soma's getLabel() hook which takes an optional second parameter to decide if you want a fallback to the default language if no localized name of that field is available:

Thanks a lot! ??

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Similar Content

    • By FireWire
      Hello community!

      I want to share a new module I've been working on that I think could be a big boost for multi-language ProcessWire sites.

      Some background, I was looking for a way for our company website to be efficiently translated as working with human translators was pretty laborious and a lack of updating content created a divergence between languages. I, and several other devs here, have talked about translation integrations and have recognized the power that DeepL has. DeepL is an AI deep learning powered service that delivers translation quality beyond any automated service available. After access to the API was opened up to the US, I built Fluency, a DeepL translation integration for ProcessWire.
      Fluency brings automated translation to every multi-language field in the admin, and also provides a translation tool allowing the user to translate their text to any language without it being inside a template's field. With Fluency you can:
      Translate any plain textarea or text input Translate any CKEditor content (yes, with markup) Translate page names for fully localized URLs on every page Translate your in-template translation function wrapped strings Translate modules Fluency is free, and now so is DeepL
      Since this module was first built DeepL has introduced free Developer accounts that allow anyone to start using Fluency at zero cost and beginning with the version 0.3.0 release Fluency now supports free DeepL accounts. As of June 2021 DeepL supports translation to 26 languages and continues to offer more.
      Installation and usage is completely plug and play. Whether you're building a new multi-language site, need to update a site to multi-language, or simply want to stop manually translating a site and make any language a one-click deal, it could not be easier to do it. Fluency works by having you match the languages configured in ProcessWire to DeepL's. You can have your site translating to any or all of the languages DeepL translates to in minutes (quite literally).
      Let's break out the screenshots...
      When the default language tab is shown, a message is displayed to let users know that translation is available. Clicking on each tab shows a link that says "Translate from English". Clicking it shows an animated overlay with the word "Translating..." cycling through each language and a light gradient shift. Have a CKEditor field? All good. Fluency will translated it and use DeepL's ability to translate text within HTML tags. CKEditor fields can be translated as easily and accurately as text/textarea fields.

      Repeaters and AJAX created fields also have translation enabled thanks to a JavaScript MutationObserver that searches for multi-language fields and adds translation as they're inserted into the DOM. If there's a multi-language field on the page, it will have translation added.

      Same goes for image description fields. Multi-language SEO friendly images are good to go.

      Creating a new page from one of your templates? Translate your title, and also translate your page name for native language URLs. (Not available for Russian, Chinese, or Japanese languages due to URL limitations). These can be changed in the "Settings" tab for any page as well so whether you're translating new pages or existing pages, you control the URLs everywhere.

      Language configuration pages are no different. Translate the names of your languages and search for both Site Translation Files (including all of your modules)

      Translate all of the static text in your templates as well. Notice that the placeholders are retained. DeepL is pretty good at recognizing and keeping non-translatable strings like that. If it is changed, it's easy to fix manually.

      Fluency adds a "Translate" item to the CMS header. When clicked this opens up a modal with a full translation tool that lets the user translate any language to any language. No need to leave the admin if you need to translate content from a secondary language back to the default ProcessWire language. There is also a button to get the current API usage statistics. DeepL account owners can set billing limitations via character count to control costs. This may help larger sites or sites being retrofitted keep an eye on their usage. Fluency can be used by users having roles given the fluency-translate permission.

      It couldn't be easier to add Fluency to your new or existing website. Simply add your API key and you're shown what languages are currently available for translation from/to as provided by DeepL. This list and all configuration options are taken live from the API so when DeepL releases new languages you can add them to your site without any work. No module updates, just an easy configuration. Just match the language you configured in ProcessWire to the DeepL language you want it to be associated with and you're done. Fluency also allows you to create a list of words/phrases that will not be translated which can prevent items such as brands and company names from being translated when they shouldn't

      No "translate page" - Translating multiple fields can be done by clicking multiple translation links on multiple fields at once but engineering a "one click page translate" is not feasible from a user experience standpoint. The time it takes to translate one field can be a second or two, but cumulatively that may take much longer (CKEditor fields are slower than plain text fields). There may be a workaround in the future but it isn't currently on the roadmap. See a solution below... No "translate site" - Same thing goes for translating an entire website at once. It would be great, but it would be a very intense process and take a very (very) long time. There may be a workaround in the future but it isn't on the roadmap. No current support for Inline CKEditor fields - Handling for CKEditor on-demand hasn't been implemented yet, this is planned for a future release though and can be done. I just forgot about it because I've never really used that feature personally.. Alpha release - This module is in alpha. Releases should be stable and usable, but there may be edge case issues. Test the module thoroughly and please report any bugs via a Github issue on the repository or respond here. Please note that the browser plugin for Grammarly conflicts with Fluency (as it does with many web applications). To address this issue it is recommended that you disable Grammarly when using Fluency, or open the admin to edit pages in a private window where Grammarly may not be loaded. This is a long-standing issue in the larger web development community and creating a workaround may not be possible. If you have insight as to how this may be solved please visit the Github page and file a bugfix ticket.
      Translate All Fields On A Page
      An exciting companion module has been written by @robert which extends the functionality of Fluency to translate all fields on a page at once. The module has several useful features that can make Fluency even more useful and can come in handy for translating existing content more quickly. I recommend reading his comments for details on how it works and input on best practices later in this thread.
      Get the module at the Github repo: https://github.com/robertweiss/ProcessTranslatePage
      ProcessWire  3.0+ UIKit Admin Theme That's Fluency in a nutshell. A core effort in this module is to create it so that there is nothing DeepL related hard-coded in that would require updating it when DeepL offers new languages. I would like this to be a future-friendly module that doesn't require developer work to keep it up-to-date.
      The Module Is Free
      This is my first real module and I want to give it back to the community as thanks. This is the best CMS I've worked with (thank you Ryan & contributors) and a great community (thank you dear reader).
      DeepL Developer Accounts
      In addition to paid Pro Developer accounts, DeepL now offers no-cost free accounts. Now all ProcessWire developers and users can use Fluency at no cost. Learn more about free and paid accounts by visiting the DeepL website. Sign up for a Developer account, get an API key, and start using Fluency.
      Download & Feedback
      Download the latest version here
      Github repository:
      File issues and feature requests here (your feedback and testing is greatly appreciated):
      Thank you! ¡Gracias! Ich danke Ihnen! Merci! Obrigado! Grazie! Dank u wel! Dziękuję! Спасибо! ありがとうございます! 谢谢你!

    • By daniel_puehringer
      Hi community,

      I am using the "PageTable" Module (also called "ProFields: Page Table") and the built in "Language" Module (also called "Languages Support").

      With the help of PageTable I was able to create several content elements which should usually be displayed in German(default language) and English.

      However some Content Elements should only be shown in German and NOT in English.

      Well sounds easy, right? Not so fast. I really love this CMS, but I have not found a solution for this problem yet.
      As you can see in the screenshots attached I tried to uncheck the "active" Checkbox for the english language to completely hide the content element for english users.

      However no matter what I do the german text shows on the english page.
      If I leave the "content-should-not-be-shown-in-english"(see Screenshot Number 2) blank and save the page, the page will inherit the german page url "content-element-with-simple-text-which-should-only-be-shown-in-german".

      My question therefore is:
      How can I hide a specific content-element for only one language?

      I´m using the latest processwire & module versions.

      The code which I use to render the content elements looks like this:
      //Info: contentelements is a field of type "ProFields: Page Table" <?php foreach ($page->contentelements as $element): echo($element->render()); endforeach; ?> filename: basic-page.php

      I would really appreciate your help since I haven´t found a solution after reading through quite a lot of forum posts.

      All the best,

    • By joeck
      I am struggling with an issue where my language switcher with flags sometimes doesn't show the flag.
      It works in the default language (german):

      but when the site is in english the german flag is not shown (path to image is not found):

      I don't really understand why it works if the site is shown in german but not in english..
      Code for language switcher:
      // remember what language is set to $savedLanguage = $user->language; $languageImage = $savedLanguage->image->url; echo "<li><a href='#' class='dropdown-toggle' data-toggle='dropdown'><img src='$languageImage' alt='$savedLanguage->title'> <span uk-icon='icon: chevron-down'></span></a>"; echo "<div class='uk-navbar-dropdown'>"; echo " <ul class='uk-nav uk-navbar-dropdown-nav'>"; foreach($languages as $language) { //go through all languages // if user is already viewing the page in this language, skip it if($language->id == $savedLanguage->id) continue; // if this page isn't viewable (active) for the language, display root page $viewable = true; if(!$page->viewable($language)) $viewable = false; // set the user's language, so that the $page->url and any other // fields we access from it will be reflective of the $language $user->language = $language; // output a link to this page in the other language $path = $language->image->url; $pagePath = $page->url; if(!$viewable) $pagePath = $pages->get(1)->url; echo "<li><a class='uk-text-medium' href='$pagePath' alt='$language->title'><img src='$path' alt='$language->title flag'> $language->title</a></li>"; } echo " </ul>"; echo "</div>"; echo "</li>"; // restore the original language setting $user->language = $savedLanguage; Language template:

      image field is configured as automatic (array if multiple)
      in language page (both german and english) only one image is saved
      html output of language switcher dropwon (image couldn't be loaded):

      html output when image can be displayed:

    • By snobjorn
      Here's my Norwegian language pack for ProcessWire. I've been adding translations gradually since 2015. By November 2020 the translations are completed, and up to date with the latest dev version of ProcessWire.
      For details, go to the ProcessWire Modules page …
      … and/or GitHub:
      Completed / up to date.
      Third party and PRO module translations have moved to another repository:
      The site files have been moved to a new repository for module files in Norwegian. Those translations includes translations for some free and some pro modules, see the complete list at GitHub.
    • By Juergen
      Hello @ all,
      I have created an inputfield with a configuration field in the backend where you can set a time format for every language (see screenshot below).

      As you can see both language values (default and German) have the default value(%R), but I have set different values, which were correctly stored in the DB (see screenshot below):

      As you can see the values are '%R' and '%r'.
      I have created the configuration inputfield like this:
      /** @var InputfieldText $f */ $languages = $this->wire('languages'); $f = $this->wire('modules')->get('InputfieldText'); $f->attr('name+id', 'timeformat'); $f->label = $this->_('Timeformat on frontend'); $f->initValue = '%R';//default value $f->attr('value', $this->timeformat ? $this->timeformat : '%R'); $this->message($this->get('timesformat')); if($languages) { $f->useLanguages = true; foreach($languages as $language) { if($language->isDefault()) continue; $f->set("value$language", (string) $this->get("timeformat$language->id")); } } $f->inputType = 'text'; $f->description = $this->_('Please enter the time format that the times should appear on the frontend in strftime format.'); $f->notes = sprintf($this->_('For example shows the time as 08:00, as 08:00 AM. You can find more examples at %s.'), '<a href="https://www.php.net/manual/de/function.strftime.php">https://www.php.net/manual/de/function.strftime.php</a>'); $f->columnWidth = 100; The important part here is:
      if($languages) { $f->useLanguages = true; foreach($languages as $language) { if($language->isDefault()) continue; $f->set("value$language", (string) $this->get("timeformat$language->id")); } } I have borrowed the code from the DateTimeInputfield (https://github.com/processwire/processwire/blob/master/wire/modules/Inputfield/InputfieldDatetime/InputfieldDatetime.module), but the field values will be always populated with the default value ('%R').
      Are I am missing something? Does anyone has experience with multilanguage fields and could help me out?
      Thanks in advance.
  • Create New...