area17 / twill

Twill is an open source CMS toolkit for Laravel that helps developers rapidly create a custom admin console that is intuitive, powerful and flexible. Chat with us on Discord at https://discord.gg/cnWk7EFv8R.
https://twillcms.com
Apache License 2.0
3.72k stars 568 forks source link

Translations with nested modules does not pick correct slug translation for parent. #2640

Open plokko opened 1 month ago

plokko commented 1 month ago

Description

Translations with nested modules does not pick correct slug translation for parent. For example if i create a nested category in italian and english where parent slug translates to:

I also have the same problem with parend-child nested modules (ex. nested translable categories with articles)

Steps to reproduce

Create a nested module with translation, create a child node and try to switch different language. The

Expected result

Nested modules should show slug on correct translation.

Actual result

Parent slug is not translated on language change.

Versions

Twill 3.3.1 Laravel 10/11 (tested on both) Php 8.2/8.3 Mysql 8

Temporary solution

After a lot of fiddling i found an improvised solution

Original code:

class PageController extends NestedModuleController
{
    //...

    protected function form(?int $id, TwillModelContract $item = null): array
    {
        $item = $this->repository->getById($id, $this->formWith, $this->formWithCount);

        $this->permalinkBase = $item->ancestorsSlug;

        return parent::form($id, $item);
    }
}

We will save all the translation for the permalinks and return them from getLocalizedPermalinkBase

class PageController extends NestedModuleController
{
    //...
    /// we will store localized slugs here:
    protected array $localizedPermalinkBase = [];
    protected function form(?int $id, ?TwillModelContract $item = null): array
    {
        $item = $this->repository->getById($id, $this->formWith, $this->formWithCount);

        ///default locale ancestor slug
        $this->permalinkBase = $item->ancestorsSlug;
        ///multiple locale ancestor slugs
        $locales = config('translatable.locales');
        $this->localizedPermalinkBase = [];
        foreach (config('translatable.locales') as $locale) {
            $this->localizedPermalinkBase[$locale] = $item->getAncestorsSlug($locale);
        }

        return parent::form($id, $item);
    }
    protected function getLocalizedPermalinkBase(): array
    {
        /// this function is called on parent::form so we should be safe
        return $this->localizedPermalinkBase;
    }
}