[英]Cakephp: Adding multiple records to single Model with one comman field
I've wanted to add multiple records to a single model in cakephp. 我想在cakephp中将多个记录添加到单个模型中。 I've been followed his tutorial http://bit.ly/1jjR1U5 and it works like charm.
我一直关注他的教程http://bit.ly/1jjR1U5 ,它的工作原理就像魅力。 But I need minor tweaking from his code.
但是我需要对他的代码进行一些细微的调整。 I need to make one field in the form as common for all the multiple records and save the model.
我需要将所有多个记录的表单中的一个字段设置为通用字段并保存模型。 I've explained below clearly his code and what I need.
我在下面清楚地解释了他的代码和我所需要的。
Below is his code to add multiple records to single model. 以下是他的代码,可将多个记录添加到单个模型中。 In add.ctp:
在add.ctp中:
echo $this->Form->create('Model');
for($i = 0; $i < $count; $i++){
echo $this->Form->input("Model.$i.field1", array());
echo $this->Form->input("Model.$i.field2", array());
echo $this->Form->input("Model.$i.field3", array());
echo $this->Form->input("Model.$i.field4", array());
}
echo $this->Form->end('add');
In Controller, ie ModelController.php inside add() action, 在Controller中,即在add()动作内部的ModelController.php中,
function add($count = 1){
if($this->request->is('post')){
if($this->Model->saveAll($this->request->data['Model'])){
$this->Session->setFlash(__('The Model has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The Model could not be saved. Please, try again.'));
}
$this->redirect(array('action' => 'index'));
}
$this->set('count', $count);
}
The above code will create multiple inserts in the table. 上面的代码将在表中创建多个插入。 What I want is in the add.ctp form,
我想要的是在add.ctp表单中,
echo $this->Form->create('Model');
echo $this->Form->input("field1", array());
for($i = 0; $i < $count; $i++){
echo $this->Form->input("Model.$i.field2", array());
echo $this->Form->input("Model.$i.field3", array());
echo $this->Form->input("Model.$i.field4", array());
}
echo $this->Form->end('add');
Here I want the Field 1 to be common to the records to be inserted in the table. 在这里,我希望字段1对于要插入表中的记录是公用的。 I don't want to loop it, because client have to select same option for field 1 in each iteration.
我不想循环它,因为客户端必须在每次迭代中为字段1选择相同的选项。 If anybody knows how to achieve this using cakephp controller or form, please share your suggestions.
如果有人知道如何使用cakephp控制器或表单实现此目的,请分享您的建议。
Try this 尝试这个
$this->request->data = Hash::insert($this->request->data, 'Model.{n}.field1', $this->request->data['Model']['field1']);
$this->request->data = Hash::remove($this->request->data, 'Model.field1');
if($this->Model->saveAll($this->request->data['Model'])) {
// your stuff goes here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.