OmgDef / yii2-multilingual-behavior

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

Cannot Insert Data To Model #37

Closed davidtim closed 9 years ago

davidtim commented 9 years ago

sorry to ask silly question, I tried $form->field($model, 'title')->textInput(['maxlength' => 255]); data inserted to table Post, but not insert to PostLang

OmgDef commented 9 years ago

@davidtim in my case it works fine. Need more info. Can you paste model and controller?

davidtim commented 9 years ago

Here is Post model


namespace app\models;

use Yii;
use omgdef\multilingual\MultilingualBehavior;
use omgdef\multilingual\MultilingualQuery;
/**
 * This is the model class for table "post".
 *
 * @property integer $id
 * @property string $created_at
 * @property string $updated_at
 * @property integer $enabled
 *
 * @property PostLang[] $postLangs
 */
class Post extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'post';
    }

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

    public static function find()
    {
        return new MultilingualQuery(get_called_class());
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            //[['created_at', 'updated_at'], 'required'],
            [['created_at', 'updated_at'], 'safe'],
            [['enabled'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'enabled' => 'Enabled',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPostLangs()
    {
        return $this->hasMany(PostLang::className(), ['post_id' => 'id']);
    }
}

And here is the controller

namespace app\controllers;

use Yii;
use app\models\Post;
use app\models\PostSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\PostLang;

/**
 * PostController implements the CRUD actions for Post model.
 */
class PostController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Post models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PostSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Post model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Post model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Post();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
//            $post_lang = new PostLang();
//            $post_lang->load(Yii::$app->request->post());
//            $model->link('postLangs', $post_lang);

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Post model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Post model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Post model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Post the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Post::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
davidtim commented 9 years ago

well after awhile I change actionCreate then I'm able to save. Please tell me if you have another solution public function actionCreate() { $model = new Post();

    if ($model->load(Yii::$app->request->post())) {
        $model->save();
        $post = (Yii::$app->request->post());
        foreach($model->languages as $language){
            $post_lang = new PostLang();
            $post_lang->title = $post["Post"]["title_$language"];
            $post_lang->content = $post["Post"]["content_$language"];
            $post_lang->language = $language;
            $post_lang->load(Yii::$app->request->post());
            $model->link('postLangs', $post_lang);
        }
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}
OmgDef commented 9 years ago

@davidtim First of all, you should include default language in languages

Like this

            'ml' => [
                'class' => MultilingualBehavior::className(),
                'languages' => [
                    'kh' => 'Khmer',
                    'en-US' => 'English',
                    'ru' => 'Russian',
                ],
                //'languageField' => 'language',
                //'localizedPrefix' => '',
                //'requireTranslations' => false',
                //'dynamicLangClass' => true',
                //'langClassName' => PostLang::className(), // or namespace/for/a/class/PostLang
                'defaultLanguage' => 'ru',
                'langForeignKey' => 'post_id',
                'tableName' => "{{%postLang}}",
                'attributes' => [
                    'title', 'content',
                ]
            ],

Also, in your controller modify findModel method

Example

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

Yes I did that already, but still have no luck

OmgDef commented 9 years ago

@davidtim add validation rules Example

[['title', 'content'], 'required'],
[['title', 'content'], 'string'],
davidtim commented 9 years ago

@OmgDef Thank you so much it's working now as stupid as I am, I don't add the validation rules

yack01 commented 4 years ago

It's a good idea to add validation rules to installation manual, @OmgDef .