OmgDef / yii2-multilingual-behavior

Yii2 port of the yii-multilingual-behavior.
146 stars 60 forks source link

Get post for current language from postLang table #3

Closed loveorigami closed 9 years ago

loveorigami commented 9 years ago

I have small problem with this behavior

use omgdef\multilingual\MultilingualBehavior;
use omgdef\multilingual\MultilingualQuery;

    public function behaviors()
    {
        return [
            'ml' => [
                'class' => MultilingualBehavior::className(),
                'languages' => [
                    'ru' => 'Russian',
                    'en-US' => 'English',
                ],
                //'languageField' => 'language',
                //'localizedPrefix' => '',
                'forceOverwrite' => true,
                'dynamicLangClass' => false,
                //'langClassName' => PostLang::className(), // or namespace/for/a/class/PostLang
                'defaultLanguage' => \Yii::$app->params['defaultLanguage'],
                'langForeignKey' => 'post_id',
                'tableName' => "{{%post__lang}}",
                'attributes' => [
                    'title', 'content',
                ]
            ],
        ];
    }

    public static function find()
    {
        $q = new MultilingualQuery(get_called_class());
        $q->localized();
        return $q;
    }

postlang

2222

3333

I think

loveorigami commented 9 years ago

and also then i added rules to Post, as required, the item not saved

    /**
     * @ Rules from Post model
     */
    public function rules()
    {
        return [
            [['title', 'content'], 'required'],
            [['content'], 'string'],
            [['title'], 'string', 'max' => 255],
        ];
    }

if I commented this rules and added to PostLang model - validation not working

// rules from PostLang model
    public function rules()
    {
        return [
            [['post_id', 'language'], 'required'],
            [['post_id'], 'integer'],
            [['content'], 'string'],
            [['language'], 'string', 'max' => 6],
            [['title'], 'string', 'max' => 255]
        ];
    }
OmgDef commented 9 years ago

@loveorigami Can you paste code of findModel method from your controller? It seems you doesn't call multilingual() scope

Example

    protected function findModel($id)
    {
        if (($model = Artist::find()->notRemoved()->multilingual()->andWhere(['id' => $id])->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
loveorigami commented 9 years ago

Thanks. I changed PostController to

    protected function findModel($id)
    {
        if (($model = Post::find()->multilingual()->andWhere(['id' => $id])->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

now added to postLang table 2 rows. It is fine.

But it is problem with validation and view

  1. rules in Post model
    public function rules()
    {
        return [
            [['title', 'content'], 'required'],
            [['content'], 'string'],
            [['title'], 'string', 'max' => 255],
            [['active'], 'integer'],
        ];
    }

if I added new post - post not created if I update post - post updated successfully

  1. Next problem
  2. Locale ru. In grid view i have russian text
  3. I change locale to en. Make translate to en. Updated good
  4. I change locale to ru. In grid view i have russian text. Next, I want edited russian text, but in form and in view I have previos data (from english translation). This data get from Post table, not from PostLang see on images 001 002 003 004
    • Next I added localized method to PostController and have
    protected function findModel($id)
    {
        if (($model = Post::find()->localized('ru')->multilingual()->andWhere(['id' => $id])->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

but method localized('ru') not give effect

Summary

OmgDef commented 9 years ago

First of all... You should read docs. You don't need change locale to edit a translation. Both translations must be saved via one form. Validations rules work correctly. You get validation errors, because you configure your app to require all translations have title and content attributes, but your form have values of required attributes only for default language.

And so, you should remove ->localized('ru') from findModel($id)

Also, your form should be similar to (if default language is Russian):

$form->field($model, 'title')->textInput(['maxlength' => 255]);
$form->field($model, 'title_en')->textInput(['maxlength' => 255]);

$form->field($model, 'content')->textInput();
$form->field($model, 'content_en')->textInput();

Then, a new model will have all required fields. I recommend you to use dynamic model if you doesn't need additional logic for translations.

Example from my app (attributes for different translations in different tabs) 2014-10-29 18 29 21

Also if you set forceOverwrite to false title and content will be required only for default language. So, if current locale translation is not set default language translation will be used for output. I think it's very common.

loveorigami commented 9 years ago

Sorry for my english ). Доки я конечно же читал. Но... после того, как познакомился с вашим бихевиром в статье http://www.elisdn.ru/blog/40/yii-based-multilanguage-site-content-translations

Там рассматривался вариант в числе прочих с хранением переводов в основной таблице, префиксируя значения полей языками (title_en, title_ru)...

Оставшееся впечатление от статьи способствовало тому, что строки

$form->field($model, 'content')->textInput();
$form->field($model, 'content_en')->textInput();

я мысленно отнес к этому случаю и не рассматривал вовсе, поскольку у меня переводы хранятся в отдельной таблице.

Большое спасибо за пояснения и отдельная благодарность за полезное расширение!

Пошел пробовать и внимательно перечитывать инструкцию ) !

OmgDef commented 9 years ago

@loveorigami Удачи в начинаниях :)