Update with two model Yii2

0

I'm studying on Yii2 and I do not have much knowledge of the framework.

I'm having trouble updating database data in two different models (Student and Address).

The idea is simple, load the view with the student data (which has the address also, but there is an address-only model).

Student Update (Controller):

public function actionUpdate($id){
        $model = $this->findModel($id);        

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

        return $this->render('update', [
            'model' => $model,
        ]);      
}

In the Student model I have the following method:

public function getEndereco0(){
        return $this->hasOne(Enderecos::className(), ['id' => 'endereco']);
}

EER image:

The create is picking up right. I just have this doubt in the update, who to call, how, where and etc ...

    
asked by anonymous 10.05.2018 / 04:44

1 answer

3

You need to have both models on your Update form (Student and Address), and on the controller fetch the Student, and after the student, fetch the Address using the foreign key that will be in the Student table:

I've removed this example from documentation :

Controller

namespace app\controllers;

use Yii;
use yii\base\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use app\models\User;
use app\models\Profile;

class UserController extends Controller
{
    public function actionUpdate($id)
    {
    $user = User::findOne($id);
    if (!$user) {
        throw new NotFoundHttpException("The user was not found.");
    }

    $profile = Profile::findOne($user->profile_id);

    if (!$profile) {
        throw new NotFoundHttpException("The user has no profile.");
    }

    $user->scenario = 'update';
    $profile->scenario = 'update';

    if ($user->load(Yii::$app->request->post()) && $profile 
     ->load(Yii::$app->request->post())) {
        $isValid = $user->validate();
        $isValid = $profile->validate() && $isValid;
        if ($isValid) {
            $user->save(false);
            $profile->save(false);
            return $this->redirect(['user/view', 'id' => $id]);
        }
    }

    return $this->render('update', [
        'user' => $user,
        'profile' => $profile,
    ]);
    }
}

View

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'user-update-form',
    'options' => ['class' => 'form-horizontal'],
]) ?>
    <?= $form->field($user, 'username') ?>

    ...other input fields...

    <?= $form->field($profile, 'website') ?>

    <?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>
    
16.05.2018 / 17:34