Using 2 or more models in a form

Hi, I have 3 tables
Users Table | Subjects Table | Users Subjects Table
id (Primary Key) | id (Primary Key) | id (Primary Key)
first_name | subject_name | user_id (Foreign Key)
last_name | created_date | subject_id (Foreign Key)
created_date | updated_date | subject_price
updated_date | | created_date
| | updated_date

We have created 3 models (Users, Subjects and UsersSubjects), we are trying to create users edit profile page where we have to provide features to edit user details along-with subjects. A User can choose multiple subjects.

public function actionEditProfile()
{
$id = Yii::$app->user->identity->getId();
    $user = Users::findOne($id);
    if (!$user) {
        throw new NotFoundHttpException("The user was not found.");
    }
    
    $profile = UsersSubjects::find()->where(["user_id"=>$user->id])->all();
//	$profile = UsersSubjects::findOne($user->id);
    /*
    if (!$profile) {
        throw new NotFoundHttpException("The user has no profile.");
    }
    */
    $user->scenario = 'update';
//    $profile->scenario = 'insert';
    
    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(['site/dashboard', 'id' => $id]);
        }
    }
    
    return $this->render('edit-profile', [
        'user' => $user,
        'subject' => $profile,
    ]);
}

View Page:

<?= $form->field($subject, 'subject_id[]')->widget(Select2::classname(), [ 'data'=>ArrayHelper::map(Subjects::find()->orderBy('subject_name')->all(), 'id', 'subject_id'), 'language'=>'en', 'options'=>['placeholder'=>'Select a subject...','id'=>'subject_id'], 'pluginOptions'=>['allowClear'=>true], ]); ?>

I am getting error $profile is not an object error. Basically we want to create feature to modify subjects here. Can you please help?

The find()->all() will be returning and array of models. It appears you want to work with a single record/model and you may want to change that to find()->one(). The error is because $profile is an array rather than an object.

Yes, I agree, but to get the desired result, how we should write.

You may have to use Model::loadMultiple() load post data into an array of models. Refer to: Collecting Tabular Input

Hopefully that is inline with what you are trying to do.

If you want to dynamically change those, Yii have good example in forms section of the Guide,
But I will suggest that you look at this extension:

1 Like