miércoles, 19 de octubre de 2016

How to save multiple related models in Yii - Add For YII2

Hi, ther is a sample and dimple code for a form with a two models ( TABLES ) , the credits : ORIGINAL! Remember, the functionality work by esaverelatedbehavior yii extension
1. Create Tables Fathers and Children.
2. Generate model and Controller with the GII plugging normaly.
3. Copy the code from the sample publications.
4. Adjust the controller code with this:

public function actionCreate() 
{ $model = new Fathers; 
// Uncomment the following line if AJAX validation is needed $this->performAjaxValidation($model); 
 if (isset($_POST['Fathers'])) 
     { $model->attributes = $_POST['Fathers']; 
        echo $model->name; 
        if (isset($_POST['Children']))
            { $model->childrens = $_POST['Children']; } 
             // Se relacionan los hijos con la relación entre las tablas del modelo. 
       if ($model->saveWithRelated('childrens')) 
           $this->redirect(array('view', 'id' => $model->id)); 
       else 
             $model->addError('children', 'Error occured while saving children.'); 
    }
 $this->render('create', array( 'model' => $model, )); 
}
 .... and this corrections too :

 public function actionUpdate($id)
    {
        $model = $this->loadModel($id);

       
// Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
 

        if (isset($_POST['Fathers']))
        {
            $model->attributes = $_POST['Fathers'];
            if (isset($_POST['Children']))
            {
                $model->childrens = $_POST['Children'];
            }
            if ($model->saveWithRelated('childrens'))
                $this->redirect(array('view', 'id' => $model->id));
            else
                $model->addError('children', 'Error occured while saving children.');
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }



And finaly:
public function actionLoadChildByAjax($index)
    {
        $model = new Children;
        $this->renderPartial('child/_form', array(
            'model' => $model,
            'index' => $index,
//            'display' => 'block',
        ), false, true);
    } 
 


This is the result:
  
 

Thank's for you comments.
 

No hay comentarios:

Publicar un comentario