Search code examples
phpactiverecordyii2yii2-basic-app

yii2 - how to save input in one form and automatically update another table


i have condition that has been bothering me sometimes. i have two models sewalocker and loker, these two models are related. i have a form in sewalockers that required to fill locker number as loker_id. when the form is submitted, i want status of selected loker_id assigned as 'loaned' not 'available' any more in loker table. how do i do that?

here is my sewaController :

<?php

namespace app\controllers;

use Yii;
use app\models\SewaLocker;
use app\models\sewaSearch;
use app\models\loker;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;


class SewaController extends Controller
{
 public function behaviors()
 {
    return [
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['post'],
            ],
        ],
    ];
}

/**
 * Lists all SewaLocker models.
 * @return mixed
 */
public function actionIndex()
{
    $searchModel = new sewaSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

/**
 * Displays a single SewaLocker model.
 * @param integer $id
 * @return mixed
 */
public function actionView($id)
{
    return $this->render('view', [
        'model' => $this->findModel($id),
    ]);
}

/**
 * Creates a new SewaLocker model.
 * If creation is successful, the browser will be redirected to the 'view' page.
 * @return mixed
 */
public function actionCreate()
{
    $model = new SewaLocker();
    $loker = new loker();

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

Solution

  • In create you should do this way

    if the SewaLocker model is saved you then can retrive the right loker model adn update..

    public function actionCreate()
    {
        $model = new SewaLocker();
    
    
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $loker = $this->findLokerModel($model->locker_id);
            $loker->status ="Loaned not available";
            $loker->save();
    
            return $this->redirect(['view', 'id' => $model->id_sewa]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    
    protected function findLokerModel($id)
    {
        if (($model = Loker::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }