Update with two Yii2 models

Asked

Viewed 199 times

0

I am studying about Yii2 and do not have much knowledge of the framework.

I’m having difficulty updating data in the database that are in two different models (Student and Address).

The idea is simple, load the view with the student’s data (which has the address as well, 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']);
}

Picture of the EER:

ERR

create is getting it right. I’m just having this question in the update, who to call, how, where and etc...

1 answer

3


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

I took 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() ?>
  • 1

    Yes, exactly! I had succeeded and forgotten the question here rsrs but it’s correct. Obg guy!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.