开发者

How to create new records in multiple tables at the same time?

开发者 https://www.devze.com 2023-01-08 05:09 出处:网络
I was wondering how can I implement a view that allows the user to enter multiple(unknown) number of records in related models..

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 开发者_StackOverflow社区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 ..


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消