views:

34

answers:

2

Hello all,

I was wondering how can I implement a view that allows the user to enter multiple(unknown) number of records in related models..

for example, I have two models called groups and users. And I want to implement a view that allows me to create a group ( which is easy ) and in the same view let me create multiple number of users who belong to this group.

I hope that my question is clear, if not just let me know ..

+1  A: 

In the backend, use a saveAll($data), preparing your data like:

// Prepare the data for the Group hasMany User
$data = array('Group' => array(
                'id' => 5, 
                'name' => 'my group',
                'User' => array(
                  array('id'=>1,'username' => 'john'),
                  array('id'=>2,'username' => 'pachelbel'))
                )
              )

// OR if it's being passed in, just use $this->data in place of $data

// Save all the data
$this->Group->saveAll($data)

In the view, you want to prepare your form such that it has correctly array'd keys:

<form id="GroupCreateForm" method="post" action="/groups/create">
  <input type="hidden" name="data[Group][id]" value="5" />
  <input type="hidden" name="data[Group][name]" value="my group" />
    <input type="hidden" name="data[Group][User][0][id]" value="1" />
    <input type="hidden" name="data[Group][User][0][username]" value="john" />
    <input type="hidden" name="data[Group][User][1][id]" value="2" />
    <input type="hidden" name="data[Group][User][1][username]" value="pachelbel" />
</form>

If you want to dynamically add users to the form, consider using javascript to inject new input elements.

See this for more info.

Jasie
Thanx for your reply . I read that post in the cakephp's cookbook . what about the front end .. how can I implement the view ?
dejavu
Check the edit, see if that helps.
Jasie
That's good enough . I can do the rest from here.I appreciate your help Jasie.
dejavu
Also, consider using transactions!
sibidiba
@sibidiba Thanks for your suggestion, I'll look into that.
dejavu
+1  A: 

You can do it smarter with using Cake's Form helper. In the example above you can rewrite like this:

<?php
echo $this->Form->Create('Group');
echo $this->Form->input('Group.id');
echo $this->Form->input('Group.name');
for($i=0;$i<10;$i++){
   $this->Form->input('User.'.$i.'.id');
   $this->Form->input('User.'.$i.'.name');
}
?>

This way you can benefit from auto error handling as well as field values population.

Nik