Masih Raad
Masih Raad

Reputation: 11

What part of yii2 code must be change to update?

this code must be update cars and users form database but when operate create new field and not update, what part of them must be change to update a field ?

I using YII2 framework and this code in controller.

    public function actionUpdate($id)
{
    $model = new JunkForm();
    $cars = CarsForm::find()->all();
    $carDropDown = [];
    foreach ($cars as $car) {
        $carDropDown[$car->id] = $car->car_name . ' (' . $car->car_color . ')';
    }
    $users = UserForm::find()->all();
    $userDropDown = [];
    foreach ($users as $user) {
        $userDropDown[$user->id] = $user->user_name . ' (' . $user->user_family . ')';
    }
    if ($model->load(yii::$app->request->post())) {
        foreach ($model->carIds as $carId) {
            foreach ($model->userIds as $userId) {
                $oldJunk = JunkForm::find()->where(['users_id' => $userId])->andWhere(['cars_id' => $carId])->one();
                if (empty($oldJunk)) {
                    $newJunk = new JunkForm();
                    $newJunk->cars_id = $carId;
                    $newJunk->users_id = $userId;
                    $newJunk->save();
                }
            }
        }
    }

    $model = new JunkForm();
        return $this->render('junk_form', [
        'model' => $model,
        'carDropDown' => $carDropDown,
        'userDropDown' => $userDropDown
        ]);
}

Upvotes: 0

Views: 33

Answers (1)

Masih Raad
Masih Raad

Reputation: 11

this :

$newJunk = new JunkForm();
                    $newJunk->cars_id = $carId;
                    $newJunk->users_id = $userId;
                    $newJunk->save();

change to this :

$newJunk = JunkForm::find()->where(['id' => $id])->one();
                    $newJunk->cars_id = $carId;
                    $newJunk->users_id = $userId;
                    $newJunk->save();

Upvotes: 1

Related Questions