很好的问题,我花了很长时间才找到解决问题的最佳方法。
CodeIgniter表单验证库很棒,但只能与适当的视图和控制器一起使用,因此在开发前端标签时它不能开箱即用。
通常,提交前端表单的首选方式是在您的 upd.addon.php 文件中注册一个“操作”(我猜您已经为您的submit_form()
函数这样做了)。然后为它分配一个数字,您可以使用 url/index.php?ACT=37
或类似的内容发布该数字。这是一个很好的系统,因为这意味着我们知道表单提交来自我们的模块。但是,对于输入表单,这是一个障碍,因为这意味着我们无法重新填充输入字段。因此,您需要将输入表单配置为回发到当前 URL,并等待模板引擎尝试呈现您的标签,然后再处理表单提交。
实现这一点的最简单且视觉上最丑陋的方法是使用$this->EE->output->show_user_error(FALSE, array_of_errors)
. 您实际上可以从一个操作或在您的模块代码中使用它。它显示了我们都知道和讨厌的标准灰色 EE 消息页面。
有了这样的介绍,您可能知道解决方案不会那么简单,对吧?这是实现内联错误检查的标记函数的框架:
function my_form()
{
// load default tag variables
$tag_vars = array();
$tag_vars[0] = array(
'first_name' => '',
'error:first_name' => '',
'last_name' => '',
'error:last_name' => ''
);
// handle a form submission
if ($this->EE->input->post('my_form_hidden') == '1'))
{
// load POST data into tag
$tag_vars[0]['first_name'] = $this->EE->input->post('first_name', TRUE);
$tag_vars[0]['last_name'] = $this->EE->input->post('last_name', TRUE);
// use CI validation library to check submission
$this->EE->load->helper('form');
$this->EE->load->library('form_validation');
$this->EE->form_validation->set_rules('first_name', 'lang:first_name', 'required');
$this->EE->form_validation->set_rules('last_name', 'lang:first_name', 'required');
$valid_form = $this->EE->form_validation->run();
if ($valid_form)
{
// probably save something to database, then redirect
}
else
{
$form_errors = array();
foreach (array('first_name', 'last_name') as $field_name)
{
$field_error = form_error($field_name);
if ($field_error)
{
$form_errors[] = $field_error;
$tag_vars[0]['error:'.$field_name] = $field_error;
}
}
if ($this->EE->TMPL->fetch_param('error_handling') != 'inline')
{
// show default EE error page
return $this->EE->output->show_user_error(FALSE, $form_errors);
}
}
}
// parse and output tagdata
$out = $this->EE->functions->form_declaration(array(
'action' => $this->EE->functions->fetch_current_uri(),
'hidden_fields' => array('my_form_hidden')));
$out .= $this->EE->TMPL->parse_variables($tagdata, $tag_vars);
return $out.'</form>';
}
这样,设计者可以error_handling="inline"
在标签中指定他们是否需要内联错误,否则他们将被重定向到标准错误表单。如果他们确实请求内联错误处理,他们只需要确保他们的输入看起来像这样:
<input type="text" name="first_name" value="{first_name}" />
{error:first_name}
注意我们与表单一起提交的隐藏字段,这使我们能够确保我们只处理此表单的提交,而不是页面上的任何其他表单,例如登录表单或其他东西。如果您在一个页面上有多个表单实例(例如在通道条目循环内或其他地方),您将需要实施一些技巧以确保您只处理提交的表单实例,例如通过提交entry_id 也作为隐藏字段。
很高兴得到所有文档,希望这对其他 EE 开发人员也有用!