Activeform And Empty Related Models

Hi all,

I’ve an activeform to collect tabular input with 1 model repeated 4 times.

This model has 3 BELONGS_TO relations and one of this has another relation BELONGS_TO: User->Registry->Address

This is my code:


for($i = 0; $i < 4; $i++) {

    $users[] = new User();

}


$form = $this->beginWidget('bootstrap.widgets.TbActiveForm',array(

	'id'=>'tb-form',

));


foreach ($users as $i => $user) {

    echo TbHtml::activeTextField($user, "[$i]name");

    echo TbHtml::activeTextField($user, "[$i]registry[field]");

    echo TbHtml::activeTextField($user, "[$i]registry[address][other]");

}


$this->endWidget();

Into my action:


$model = new User();

$model->attributes = $_POST['User'][0];

But $model->registry it’s null and obviously address.

My question is:

Is there a way to initialize an empty model and all related object? (ie: $u = new User(); and I’ve also $u->registry and $u->registry->address, so that I can write in my form [$i]registry.field and [$i]registry.address.other)

Or exists a way to initialized all related models from my previous form?

thanks in advance

Hi markux,

Yii’s relational active record works only for reading. It doesn’t handle automatically the creating or updating of the related objects.

One thing you could try could be initializing the related objects manually:




for($i = 0; $i < 4; $i++) {

    $user = new User();

    $user->registry = new Registry();

    $user->registry->address = new Address();

    $users[] = $user;

}



But I’m not sure this works for active form and massive assignment.




    // does this work?

    echo TbHtml::activeTextField($user, "[$i]registry[field]");

    echo TbHtml::activeTextField($user, "[$i]registry[address][other]");






    // does this populate 'registry' and 'address'?

    $model = new User();

    $model->attributes = $_POST['User'][0];



It may sound a little stupid, but I would add virtual attributes in User model for handling the necessary fields of ‘Registry’ and ‘Address’.




    echo TbHtml::activeTextField($user, "[$i]registry_field");

    echo TbHtml::activeTextField($user, "[$i]address_field");






    $model = new User();

    $model->attributes = $_POST['User'][0];

    $registry = new Registry();

    $registry->field = $model->registry_field;

    $address = new Address();

    $address->field = $model->address_field;

    $address->save();

    $registry->address_id = $address->id;

    $registry->save();

    $model->registry_id = $registry->id;

    $model->save();



Or, I would rather create a dedicated CFormModel for this.

Maybe the CActiveRecord.init() method could help you ?

I tried it and It’s doesn’t work for active form and massive assignment.

I solved with classic solution: initialization of each model and its validation.

thanks