S
S
Skrolea2016-04-17 00:52:45
Yii
Skrolea, 2016-04-17 00:52:45

How to save the model by iterating?

I want to keep bilingual content. The form

<?php $form = ActiveForm::begin(); ?>

    <?= $form->field($aboutLang_ru, 'title')->textInput() ?>

    <?= $form->field($aboutLang_ru, 'content')->textInput() ?>
    
    <?= $form->field($aboutLang_en, 'title')->textInput() ?>

    <?= $form->field($aboutLang_en, 'content')->textInput() ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

and controller
public function actionCreate() {
        $model = new Post();
        $aboutLang_ru = new PostLang();
        $aboutLang_en = new PostLang();
        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                                
                    $dbPost = new PostLang();
                    $dbPost->title = $aboutLang_ru->title;
                    $dbPost->content = $aboutLang_ru->content;
                    $dbPost->lang_id = ////////;
                    $dbPost->post_id = $model->id;
                    $dbPost->save();
             
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('_form', [
                        'model' => $model, 'aboutLang_ru' => $aboutLang_ru, 'aboutLang_en' => $aboutLang_en]);
        }
    }

Here's how I can iterate over saving so that it saves first from $aboutLang_ru, and then from $aboutLang_en? Different records in the table and with different lang_id, but with the same post_id?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2016-04-17
@webinar

$langs = ['aboutLang_ru','aboutLang_en'];
foreach($langs as $lang){
// тут код
}

Or if you follow the normal path, then you should read here:
www.yiiframework.com/doc-2.0/guide-input-multiple-...
And if it’s absolutely correct, but translations should be in related tables, and you can save them in the model.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question