我是 cakephp 的新手。我得到了一个有 5 个输入的表格。我的表单应该能够保存 1 个用户输入或全部 5 个输入。当用户填写所有 5 个输入时,我可以保存,但是,当用户仅填写 1 或 2 个输入并保存时。带有创建日期(当前日期)的空格将保存在数据库中。我怎样才能只保存表单中的用户输入,而不在数据库中保存任何空字段。下面是我的添加功能。
公共函数add(){
if ($this->request->is('post')) {
$this->Item->create();
for ($i=0;$i<5;$i++){
if(empty($this->request->data['Item'][$i]['name'])){
}else{
$name = $this->request->data['Item'][$i]['name'];
$explode_name = explode(":",$name);
$this->request->data['Item'][$i]['name'] = $explode_name[0];
$this->request->data['Item'][$i]['hrid'] = $explode_name[1];
}
}
if ($this->Item->saveAll($this->request->data['Item'])) {
$this->Session->setFlash(__('The Item has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The item could not be saved. Please, try again.'));
}
}
$itemTypes = $this->Item->ItemType->find('list',array('order' =>array('ItemType.name' => 'asc')));
$this->set(compact('itemTypes'));
}
您遗漏了一件小事,那就是名称是否为空,但它为该特定索引设置了值。如果该值为空,您应该取消设置,如下所示
public function add() {
if ($this->request->is('post')) {
$this->Item->create();
for ($i=0;$i<5;$i++){
if(empty($this->request->data['Item'][$i]['name'])){
// here we are removing the empty name index so that it does not saves the result
unset($this->request->data['Item'][$i]);
}else{
$name = $this->request->data['Item'][$i]['name'];
$explode_name = explode(":",$name);
$this->request->data['Item'][$i]['name'] = $explode_name[0];
$this->request->data['Item'][$i]['hrid'] = $explode_name[1];
}
}
// also here we should check here that atleast there is one entry
if(!empty($this->request->data['Item'])){
if ($this->Item->saveAll($this->request->data['Item'])) {
$this->Session->setFlash(__('The Item has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The item could not be saved. Please, try again.'));
}
} else {
$this->Session->setFlash(__('There is no such item. Please fill value for at least one item.'));
}
}
$itemTypes = $this->Item->ItemType->find('list',array('order' =>array('ItemType.name' => 'asc')));
$this->set(compact('itemTypes'));
}
请尝试上面的代码。
在
CakePHP 2.x
你可以像下面那样做-
public function add(){
if ($this->request->is('post')) {
$this->Item->create();
$items = $this->request->data['Item']; /*Get all items Array*/
$items = array_filter(array_map('array_filter', $items)); /*Remove all empty array, only keep Array with user inputs*/
if ($this->Item->saveAll($items)) {
/*Success*/
} else {
/*Error*/
}
}
}
在
CakePHP 3.x
你可以像下面那样做-
public function add() {
if ($this->request->is('post')) {
$items = $this->request->data['Item']; /*Get all items Array*/
$items = array_filter(array_map('array_filter', $items)); /*Remove all empty array, only keep Array with user inputs*/
$entities = $this->Item->newEntities($items); /*Prepare all Data*/
if($this->Item->saveMany($entities)){ /*Save all data*/
/*Success*/
}else{
/*Error*/
}
}
}