Ada*_*tus 2 parameters codeigniter callback
(编辑:我已经意识到,或许在回调中将数组作为参数传递?)
我正在尝试研究如何将参数传递给CI中的回调函数.我已阅读文档,但除了以下内容之外没有太多内容:
要调用回调,只需将函数名称放在规则中,并使用"callback_"作为规则前缀.如果你需要在回调函数中接收一个额外的参数,只需在方括号之间的函数名之后正常添加它,如:"callback_foo [bar]",然后它将作为你的回调函数的第二个参数传递.
我要做的是创建一个回调函数,检查是否已经选择了一个本来不应该的.因此,如果有人选择"请选择"选项,则不会将其添加到数据库中.任务类型只是一个包含主键和名称字段以及大约10行的表.
控制器 所以这是我的控制器代码(减少):
function Add_Task()
{
$task_types_get = $this->task_model->Get_Task_Types();//Get available task types.
$this->options->task_types = $task_types_get->result();
$not_selectable = array(1);//Non selectable values for select. Added to callback function below for validation. These are pks.
$this->form_validation->set_rules("task_type","Task Types","required|callback__Not_Selectable[$not_selectable]");
if($this->form_validation->run())
{
//Add to db etc..
}
}
Run Code Online (Sandbox Code Playgroud)
回调 和我的回调检查是否有东西是不可选的:
function _Not_Selectable($option,$values=array())
{
if(in_array($option,$values))//Is the value invalid?
{
$this->form_validation->set_message('_Not_Selectable', 'That option is not selectable.');
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
查看 从模型返回的数据是可以的,但没有验证错误.我的观点如下:
<? $this->load->view('includes/header'); ?>
<?=form_open();?>
<div class="form_row">
<div class="form_field">
<label for="task_desc">Task Type</label>
</div>
<div class="form_field name_element" id="name-list">
<select name="task_type" id="task_select">
<? foreach($task_types as $t => $v):
echo "<option ".set_select('task_type', $v->tt_id)." value=\"{$v->tt_id}\">{$v->name}</option>\n";
endforeach;
?>
</select>
<?=form_error('task_type');?>
</div>
</div>
<?=form_submit('add_task', 'Add Task');?>
<?=form_close();?>
<? $this->load->view('includes/footer'); ?>
Run Code Online (Sandbox Code Playgroud)
错误 我得到的错误是:
A PHP Error was encountered
Severity: Warning
Message: in_array() [function.in-array]: Wrong datatype for second argument
Filename: controllers/tasks.php
Line Number: 112 (NOTE: this is the in_array line in the callback function.)
Run Code Online (Sandbox Code Playgroud)
该错误表明传递的信息不是数组,但我甚至将数组定义为默认值.我在回调函数的$ options数组上做了一个print_r(),但它打印出一个空数组.
谢谢.
问题出在这里:
"required|callback__Not_Selectable[$not_selectable]"
Run Code Online (Sandbox Code Playgroud)
这转换为字符串:
"required|callback__Not_Selectable[Array]"
Run Code Online (Sandbox Code Playgroud)
当您在PHP中将数组视为字符串时会发生这种情况.
这个问题是Codeigniter的表单验证库的限制,没有正确的方法在回调或验证规则中使用数组,你必须使用字符串.试试这个:
$not_selectable = implode('|', $your_array);
Run Code Online (Sandbox Code Playgroud)
这将是类似的东西1|4|18|33.然后按照您当前的操作设置规则,但在回调中准备管道分隔的字符串而不是数组,并用于explode()创建一个:
function _Not_Selectable($option, $values_str = '')
{
// Make an array
$values = explode('|', $values_str);
if(in_array($option,$values))//Is the value invalid?
{
$this->form_validation->set_message('_Not_Selectable', 'That option is not selectable.');
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)