Custom fields in multi language setup

I have a multi language setup with German + English, where German is the default language.

When I add a custom field in the German content file, like
MyFieldName : Some text

and in the template:
$text = $page->MyFieldName()
$text returns “Some text”, which is correct.

However, when I switch to English, and the English content file has no such field, $text also will return “Some text” taken from the German content file.

Likewise, the $page->content()->has($field) function returns true when switched to English, although only the German content file has this field.

Is this intended? I would expect an empty string rsp. “false” returned.

You can use isTranslated() to check if the field is translated:

Default is that the content of the default language is returned if the non-default field is empty.

This is actually the intended behavior.

You can work around it if you want to using the current language code to fetch the content.

Edit: Or use isTranslated like @texnixe suggested. That’s probably a better option too :slight_smile:

Thank you both.

I found also that
$page->content($lang = ‘en’)->has($field)
returns false if not translation exists.

(I think that is what you meant, Thiousi)

Yes that’s what I meant only instead of hardcoding it, you can use the current language code:

There’s also a very useful piece of code that you can use to redirect the user to an error page if the content doesn’t exist. This is used in the docs in a language switch:

<nav class="languages" role="navigation'">
  <?php foreach($site->languages() as $language): ?>
        <li<?php e($site->language() == $language, ' class="active"') ?>>
          <a href="<?php e($page->content($language->code())->language() != $site->language($language->code()), page('error')->url($language->code()), $page->url($language->code()))?>"><?php echo $language->code(); ?></a> 
  <?php endforeach ?>

Find it here:

I hope that helps !