Jump to content

change default language revisited


gebeer

Recommended Posts

I know this has been discussed in detail over the years and I read everything I could find about it in the forum. And still, no (straightforward) solution to my scenario.

My situation:

I set up a multilingual events directory site were instructors can sign in and manage their events. There is a core content area which is available in 4 languages. Instructors post their personal info and their events in only one language, but field labels need to be multilanguage. Therefore I need multilanguage page names and fields for them, too. The site has been running on Joomla/Seblod for 3 years already.

I am currently in the process of porting it to PW.

Once this is done, a skeleton of the site will be rolled out in different EU countries, so instructors in those countries have their own PW install to manage events for their country.

Of course, the default language needs to be a different one in each country. And this is where my problem lies.

I have the multilanguage setup with Language Support Page Names module and am working with multi-language fields in a 2.6.23 install.

In the original project, the default language is English. Now I need to make a copy of the site that has German as default.

Solutions that I am aware of are:

1. do a redirect for the default language homepage. For the frontend this is fine except for the /de/ appended to the home page. In the backend, the German users have language German. But German is not the default language. So when a user creates a new event, they will be presented with the German tab open for multi-language fields. When they fill in the title (PageTitleLanguage) and hit save, they get an error "Required value missing" for the title field. Because they only fill in the german title and the default (english) title is still empty, hence the error. So this is actually not a solution.

2. switch the values for multi-language fields by script (like proposed here) and rename the default's language title to "German" and adjust the URLs in the page names of the home page. While this is doable, it requires quite some effort as I will have to do this for every country.

In Joomla/Seblod I can just change the default language with one click in the backend. And I am very much missing this feature in PW  :'(

Finally, my question: Is there any way other than solution 2 to handle the situation? Maybe I missed some new features or maybe someone has come up with a way to truly change the default language programmatically.

Thanks for reading through all of this. Any help would be very much appreciated.

  • Like 1
Link to comment
Share on other sites

The thing is, if those sites will be available in different countries you shouldn't even use language support fields. So I'd try it with just removing the "data" column of each field table and renaming "date_langID" to "data". Remove all other language cols and the modules and you should be good to go with a single language site for each language you created.

But keep in mind that you'll still need to have the LanguageSupport module installed to be able to have backend translations, but no other language module should be needed.

Link to comment
Share on other sites

Thank you for your looking into this and for your input.

I still need multilingual for each country because there is a core content section that is the same for all countries. And that core content needs to be available in 4 or more languages in each country. And, honestly, I am a bit scared of manipulating the DB manually. I might break the whole site.

I will experiment with option 2 from my first post and post my findings here. That is, writing a script that swaps language content over. E.g. English content gets swapped with German content. Then just change language titles and URLs on homepage.

Link to comment
Share on other sites

@tpr

Thanks for the suggestions.

As I wrote in solution #1 in my first post, from the frontend side that solution would work. But it brings problems in the backend when users with non default language are creating pages. Because page title values only fall back from default to non default languages and not vice versa.

To illustrate this: 

user has language German assigned and creates new event. There he gets presented with the "Deutsch" Tab of the title field where he fills in his title.

post-1920-0-29100100-1447397787_thumb.pn

Now he hits save and gets an error, because there is only a german title and page name. And the default (English) title and page name do not fall back to the german value

post-1920-0-77125800-1447397923_thumb.pn 

Link to comment
Share on other sites

@tpr

Then they would be presented with a backend in English. But they should have the backend in their native language.

I also do page manipulations through frontend forms and there the user language determines for language fields which language to populate.

So your suggestion is not an option.

I am currently writing a language value swap function and will report back here.

Link to comment
Share on other sites

In my language swap function, I iterate over all page fields and swap the languages only for multi language fields

                var_dump($p->id);
		foreach ($p->template->fieldgroup as $field) {
			if($field->type instanceof FieldtypePageTitleLanguage || $field->type instanceof FieldtypeTextareaLanguage) {
				$fieldlog .= " {$field->name}";
				var_dump($p->$field);
				$$langDefault = $p->getLanguageValue($l1);
				$$lang = $p->$field->getLanguageValue($l2); //line 268

				$p->$field->setLanguageValue($l1, $$lang);
				$p->$field->setLanguageValue($l2, $$langDefault);
			}
		}

What is really boggling me is that for some pages that all have the same template basic-page, this code works fine. But for others it throws an error

Fatal error: Call to a member function getLanguageValue() on string in /var/www/utgpw/site/templates/convert.php on line 268

the var_dump reveals

int 27
object(LanguagesPageFieldValue)[372]
  public 'default' => string '404 Not Found' (length=13)
  public 'de' => string '' (length=0)
  public 'fr' => string '' (length=0)
  public 'es' => string '' (length=0)
object(LanguagesPageFieldValue)[395]
  public 'default' => string '' (length=0)
  public 'de' => string '' (length=0)
  public 'fr' => string '' (length=0)
  public 'es' => string '' (length=0)
int 1421
object(LanguagesPageFieldValue)[376]
  public 'default' => string 'Mantak Chia' (length=11)
  public 'de' => string '' (length=0)
  public 'fr' => string '' (length=0)
  public 'es' => string '' (length=0)
string '<p>test</p>' (length=11)

For the same field of type TextAreaLanguage in one case "$p->$field" returns an opject and in the other case a string. Now why is that?

Pages where this happens have been imported through the API. I can't pull up the code that I used for the import because it is some time ago. The affected pages are working fine in the frontend, though.

Link to comment
Share on other sites

No, I set $p->of(false) just before these operations. I also tried with including $p->of(false) in the foreach. 

EDIT:

@LostKobraKai : thank you!

I changed my foreach to

		foreach ($p->template->fieldgroup as $field) {
			if($field->type instanceof FieldtypePageTitleLanguage || $field->type instanceof FieldtypeTextareaLanguage) {
				$fieldlog .= " {$field->name}";
				var_dump($p->$field);
				$p->of(false);
				$$langDefault = $p->$field->getLanguageValue($l1);
				$$lang = $p->$field->getLanguageValue($l2);

			 	$p->$field->setLanguageValue($l1, $$lang);
				$p->$field->setLanguageValue($l2, $$langDefault);
			}
		}

Strange, when I tested earlier, I had the $p->of(false) before the if statement and it wouldn't do.

EDIT again:

And now I suddenly get the error again, on a different page even with $p->of(false) in place.

I just found that after reloading the edit screen for the page in the backend, the error disappears.

Link to comment
Share on other sites

Now I found a pattern.

When I have the var_dump($p->$field); in place, it is working. When I comment it out, I get the error. What can that be?

EDIT:

I don"t even need the $p->of(false) in the foreach loop. As long as thje var_dump is in place, the error is gone.

Link to comment
Share on other sites

Replacing the dynamic variable names didn't help either.

I observe that this is happening only for some pages. Now I need to go and find out what these pages have in common or what makes them different from the pages that are working.

Link to comment
Share on other sites

I managed to successfully change my default language  O0

Everything went quite smoothly, except for some strange errors that I desribed above and which might be related to my particular environment.

Here my complete function for swapping a language with the default language. Instructions for necessary steps after swapping languages are included. 

 
<?php

function swapLanguages($pages, $lang) {

	$startTime = microtime(true);
	$langDefault = "default";
	$log = ["languages" => "Swap field values for language {$langDefault} with {$lang}", "pages" =>[]];
	$languages = wire("languages");
	// get languages
	$l1 = $languages->get($langDefault);
	$l2 = $languages->get($lang);

	foreach ($pages as $p) {

		$log["pages"][$p->id] = "";
		$fieldlog = " name";

		$p->of(false);

		// swap page names
		$nameDefault = $p->localName($l1);
		$name = $p->localName($l2);

		if($nameDefault != $name && !empty($name)) {
			$p->set("name",$name);
			$p->set("status$l2",1);
			$p->set("name$l2",$nameDefault);
		} elseif($nameDefault != $name && empty($name)) {
			$p->set("status$l2",1);
			$p->set("name$l2",$nameDefault);
		}
		// iterate through all fields and swap multi language field values
		foreach ($p->template->fieldgroup as $field) {

			if($field->type instanceof FieldtypePageTitleLanguage || $field->type instanceof FieldtypeTextareaLanguage || $field->type instanceof TextLanguage) {
				$fieldlog .= " {$field->name}";
				// var_dump($p->$field); // needed this for some pages otherwise they threw an error
				// $p->of(false); // needed this for some pages otherwise they threw an error
				$langDefault = $p->$field->getLanguageValue($l1);
				$lang = $p->$field->getLanguageValue($l2);

				if( $langDefault != $lang && !empty($lang) && !empty($langDefault) ) {
					$p->$field->setLanguageValue($l1, $lang);
					$p->$field->setLanguageValue($l2, $langDefault);
				} elseif( $langDefault != $lang && empty($lang) ) {
					$p->$field->setLanguageValue($l2, $langDefault);
				} elseif( $langDefault != $lang && empty($langDefault) ) { // only needed this for pages that got created through API and had no default lang value set
					$p->$field->setLanguageValue($l1, $lang);
				}
			}
		}
		
		try {
			$p->save();
			$log["pages"][$p->id] = "Swapped values in fields: {$fieldlog}";
		} catch (Exception $e) {
			$log["pages"][$p->id] =  'Error: ' .  $e->getMessage();
		}

		$p->of(true);
	}

	// write logfile
	$logfile = fopen(wire("config")->paths->logs . "swaplanguage-log.txt", "w") or die("Unable to open file!");

	$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($log));
	foreach($iterator as $key => $value) {
		fwrite($logfile, "$key => $value\n");
	}

	fclose($logfile);

	$time_elapsed = microtime(true) - $startTime;

	echo "Finished after {$time_elapsed} seconds";

}

/* Usage:
// swapLanguages($pages->find("template=basic-page, parent=1, include=all"), "de");
// argument 1: pages array
// argument 2: language name that you want to swap with the default language
// A log file will be written to site/assets/logs/swaplanguage-log.txt.
// It contains page IDs and fields that were swapped for each page
*/

/*
// After executing this function for all required pages, following steps are needed:
// 1. load core translation files for the language that is now your default (e.g. german translation files) to Setup->languages->default
// 2. change titles of the default Language to your language (e.g. Deutsch) and the language that got swapped (e.g. English)
// 3. if default language was English before swapping: delete core translation files for the language that you swapped
// 4. if default language was not English before swapping: load the core translation files for that language
// 4. in settings for home page, change the URL for your default language and the language that you have swapped.
// Example: 
// Before swapping: default was en, swap language was de 
// After swapping: default is now de, swapped language is now en
*/
 

The function will swap page names and the contents of multi-language fields TextAreaLanguage and PageTitleLanguage.

If any of you know a more generic way of checking whether a field is multi language, other than

if($field->type instanceof FieldtypePageTitleLanguage || $field->type instanceof FieldtypeTextareaLanguage)

that would be great.

The function is also available as swap-languages.php gist

EDIT: Added field type TextLanguage to the fields that will be processed.

  • Like 3
Link to comment
Share on other sites

I am still investigating the strange behaviour of placing a var_dump() in the code preventing the error like I described in #11

Reading up on var_dump() in the PHP docs, I found this:

Note that var_dump reset()'s array internal pointer!

In the foreach that loops through the page fields, why does resetting the internal pointer of the fields array make a difference and what can I change in my code to avoid the error in the first place?

Link to comment
Share on other sites

  • 1 month later...

I don't know if this is useful

but my approach would be this:

make a different site profile for the correct default language

a site profile with the default as english, spanish, french, etc.

share the common fields, templates and components and then

just change the default language as needed.

later install different pw installation with the site profile that the language need.

Link to comment
Share on other sites

...and then

just change the default language as needed.

How would you do that? I'd be curious to know ;)

I don't mean to offend you here. Its just that my OP and the whole thread is about finding a way how to easily - or like you put it - "just" change the default language.

This can get quite complex when you already have contents for your different languages.

I really tried to find everything in the forum related to this task. And the solution I came up with is the script I posted above.

I'd be happy to find an easier way.

Your suggestion with one site profile per language can work. But then initially setting up 1 profile per language is quite a time consuming task.

I used my script to switch the default language like described in #14. And it works.

But still, and I second ivanr here, it would be fabulous to have a switch in the backend that "just" changes the default language in an easy manner :)

Link to comment
Share on other sites

But still, and I second ivanr here, it would be fabulous to have a switch in the backend that "just" changes the default language in an easy manner :)

Exactly. Meanwhile, I will test out your script on a test-install and see how it goes. Thanks for posting.

  • Like 1
Link to comment
Share on other sites

  • 2 years later...

Sorry for bumping and old topic... but it seems there is still no language-module features for swapping languages with the default? I had this issue and found that dealing with PW databases was the fastest route for me:

To swap language strings repeat this SQL for each multilanguage field:

UPDATE field_FIELDNAME s1, field_FIELDNAME s2 SET s1.data = s1.data123, s1.data123 = s2.data WHERE s1.pages_id = s2.pages_id;

FIELDNAME is your fieldname in PW and data123 is the column name for the language your are swapping the default for. Just check any multilanguage field table to see the correct column name. Finally to swap page names run this SQL:

UPDATE pages s1, pages s2 SET s1.name = s1.name123, s1.name123 = s2.name WHERE s1.id = s2.id AND s1.name123 IS NOT NULL

Obviously it is risky to tamper with databases, but this approach saved me lots of work with a big site with reasonably few fields.

The language-module should have this sort of swappery built-in.

  • Like 6
  • Thanks 3
Link to comment
Share on other sites

  • 11 months later...
On 3/22/2018 at 7:40 PM, mscore said:

Sorry for bumping and old topic... but it seems there is still no language-module features for swapping languages with the default? I had this issue and found that dealing with PW databases was the fastest route for me:

Thanks a lot for this solution @mscore! I've just switched successfully my default language from English to German by this. The only remaining step seemed to be moving "German" to the first position of "Languages" in the page tree, then I also get the "German" tab at first position when editing a text.

I really can't understand why this is no PW default feature yet -- this feature was essential for finishing my site migration to PW, and my fear of wrecking my content by a dirty workaround delayed my project probably by several months!

  • Like 1
Link to comment
Share on other sites

I still found a weird bug after having changed the default language by SQL: The "Language Support - Tabs" module doesn't work correctly any more. It does show the tabs, but on each tab the fields for both languages are shown, too.

Does anybody have a clue why this could be?

Link to comment
Share on other sites

10 hours ago, FlorianA said:

Does anybody have a clue why this could be?

There are some quirks regarding this issue, please read this report, particularly the last two comments of mine:

https://github.com/processwire/processwire-issues/issues/668

EDIT: I posted this too early by accident.

Edited by szabesz
EDIT I posted this too early by accident.
  • Like 1
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

       
      Limitations:
      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.
      Enhancements
      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
      Requirements:
      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
      https://github.com/SkyLundy/Fluency-Translation/archive/main.zip
      Github repository:
      https://github.com/SkyLundy/Fluency-Translation
      File issues and feature requests here (your feedback and testing is greatly appreciated):
      https://github.com/SkyLundy/Fluency-Translation/issues
       
      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,
      Dani


    • 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 …
      https://modules.processwire.com/modules/norwegian/
      … and/or GitHub:
      https://github.com/snobjorn/processwire-norwegian-language-pack-nb-no
      Status:
      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...