我是编码的新手。这与我过去的编码经验非常不同,我目前想做的是将数据发布到服务器并进行检查。由于输入框是动态生成的,这使我的添加功能非常混乱。
首先,对于每个数据,它必须有1个标题和1个内容,并随机编号(或没有)一个链接组(链接文本和链接),例如LinkText1,Link1,LinkText2,Link2。等等。
我想以更优雅的方式做到这一点。
我现在做的是在模型中有 2 个方法,1 个用于标题和内容,在插入它之后,返回最后一个 id,基于这个 id 附加所有其他链接组。
public function add()
{
//if save button was clicked, get the data sent via post
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
//form validation
$this->form_validation->set_rules('title', '消息標題', 'required');
$this->form_validation->set_rules('content', '消息內容', 'required');
foreach ($this->input->post() as $key => $value) {
if (strstr($key,"linkText") !== False) {
$this->form_validation->set_rules($key, '連結標題', 'required');
}
else if (strstr($key,"link") !== False) {
$this->form_validation->set_rules($key, '連結地址', 'required');
}
}
$this->form_validation->set_error_delimiters('<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>', '</strong></div>');
//if the form has passed through the validation
if ($this->form_validation->run())
{
$data_to_store = array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content')
);
//if the insert has returned true then we show the flash message
$lastID = $this->news_model->store_news($data_to_store);
if($lastID !== False){
foreach ($this->input->post() as $key => $value) {
if (strstr($key,"linkText") !== False) {
$linkText = $key;
}else if (strstr($key,"link") !== False) {
$link = $key;
}
if (isset($linkText) && isset($link)) {
$data_to_store = array(
'title' => $this->input->post($linkText),
'url' => $this->input->post($link),
'news_id' => $lastID
);
if($this->news_model->store_news_link($data_to_store)){
$data['flash_message'] = TRUE;
} else {
$data['flash_message'] = FALSE;
}
}
}
}else{
$data['flash_message'] = FALSE;
}
}else{
$data['flash_message'] = FALSE;
}
}
//load the view
$data['main_content'] = 'admin/news/add';
$this->load->view('includes/template', $data);
}
它循环了2次,并且重复了许多代码,还有比这更优雅的实现方式吗?感谢您的帮助。
您可以删除
if ($this->input->server('REQUEST_METHOD') === 'POST')
因为
$this->form_validation->run()
正在照顾它。
也请摆脱许多
$data['flash_message'] = FALSE;
只需将该行放在函数的开头,然后在需要时将其更改为 true。将其复制粘贴到整个代码中是没有意义的。
我不确定我是否理解这个问题,但我认为您正在寻找像这样的输入数组
<input name="myarray[]" ... />
CodeIgniter 可以验证这些,请参阅此处