M
M
Maxim2018-09-16 13:40:01
Yii
Maxim, 2018-09-16 13:40:01

Yii how to make one form in Single Table Inheritance?

Hello everyone!) Again with stupid questions)) Following the example of https://sohabr.net/habr/post/274925/ I made my own models. I stopped in the actionCreate action, where we add new records to the database, as well as select new ones.
In actionCreate we have something like this:

public function actionCreate()
    {
        $model = new Сar();

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

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

In this case, when selected in the form $type = 'sport', the created model will not be changed to $model = new SportCar().
How do I change the model depending on the type in the create action? I would also like to hang ajax on this and load the necessary form fields depending on the type.
I assume that the logic for creating a model must also be done in the controller, depending on the type. Perhaps I'm wrong. In the form, we make a select with types and broadcast ajax to it on the actionCreate action. After the ajax request and depending on the type, we create the desired model and load the required fields to fill in.
Tell me, do I think correctly?) Perhaps I went the wrong way at all. Maybe it was necessary to make it not a form model ... I would be very grateful !!!!!!!))))
My table turned out like this 5b9e3b231824b286824751.pngField type in this caserole

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-09-17
@myks92

public function actionCreate($type)
    {
        switch ($type){
         case SportCar::TYPE: 
           $model = new SportCar();
           break;

          ......
          default:
             $model = new Сar();
         }

in order not to do this all the time, you can put it in a private method in the controller

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question