Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to create a multi-model form in Yii? I searched the entire documentation of Yii, but got no interesting results. Can some one give me some direction or thoughts about that? Any help will be appreciable.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
342 views
Welcome To Ask or Share your Answers For Others

1 Answer

In my expirience i got this solution to work and quickly understandable

You have two models for data you wish collect. Let's say Person and Vehicle.

Step 1 : Set up controller for entering form

In your controller create model objects:

public function actionCreate() {

  $Person = new Person;
  $Vehicle = new Vehicle;

  //.. see step nr.3

  $this->render('create',array(
        'Person'=>$Person,
        'Vehicle'=>$Vehicle)
  );
}

Step 2 : Write your view file

//..define form
echo CHtml::activeTextField($Person,'name');
echo CHtml::activeTextField($Person,'address');
// other fields..

echo CHtml::activeTextField($Vehicle,'type');
echo CHtml::activeTextField($Vehicle,'number');

//..enter other fields and end form

put some labels and design in your view ;)

Step 3 : Write controller on $_POST action

and now go back to your controller and write funcionality for POST action

if (isset($_POST['Person']) && isset($_POST['Vehicle'])) {
    $Person = $_POST['Person']; //dont forget to sanitize values
    $Vehicle = $_POST['Vehicle']; //dont forget to sanitize values
    /*
        Do $Person->save() and $Vehicle->save() separately
        OR
        use Transaction module to save both (or save none on error) 
        http://www.yiiframework.com/doc/guide/1.1/en/database.dao#using-transactions
    */
}
else {
    Yii::app()->user->setFlash('error','You must enter both data for Person and Vehicle');
 // or just skip `else` block and put some form error box in the view file
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...