Joomla3自定义服务器端表单验证规则


Joomla3 custom server side form validation rule

我是joomla组件开发(J3, MVC)的新手,我正在尝试创建一个自定义服务器端表单验证规则。

我将validate="machinename"添加到我的表单字段,并创建了一个文件models'rules'machinename.php

defined('_JEXEC') or die('Restricted access');
jimport('joomla.form.formrule');
class JFormRuleMachinename extends JFormRule
{
    protected $regex = '/^[a-zA-Z_'x7f-'xff][a-zA-Z0-9_'x7f-'xff]*$/';
}

我有一个空的控制器在controllers'field.php

defined('_JEXEC') or die('Restricted access');
// import Joomla controllerform library
jimport('joomla.application.component.controllerform');
class SampleControllerField extends JControllerForm
{
}

,模型为models'field.php

defined('_JEXEC') or die('Restricted access');
// import Joomla modelform library
jimport('joomla.application.component.modeladmin');
/**
 * HelloWorld Model
 */
class SampleModelField extends JModelAdmin
{
    public function getTable($type = 'Field', $prefix = 'SampleTable', $config = array())
    {
        return JTable::getInstance($type, $prefix, $config);
    }
    /**
     * Method to get the record form.
     *
     * @param       array $data Data for the form.
     * @param       boolean $loadData True if the form is to load its own data (default case), false if not.
     * @return      mixed   A JForm object on success, false on failure
     * @since       2.5
     */
    public function getForm($data = array(), $loadData = true)
    {
        // Get the form.
        $form = $this->loadForm('com_sample.field', 'field',
            array('control' => 'jform', 'load_data' => $loadData));
        if (empty($form))
        {
            return false;
        }
        return $form;
    }
    /**
     * Method to get the data that should be injected in the form.
     *
     * @return      mixed   The data for the form.
     * @since       2.5
     */
    protected function loadFormData()
    {
        // Check the session for previously entered form data.
        $data = JFactory::getApplication()->getUserState('com_sample.edit.field.data', array());
        if (empty($data))
        {
            $data = $this->getItem();
        }
        return $data;
    }
}

我的组件名称是com_sample,一切都工作得很好(新建,编辑,删除),但后来我添加了验证规则到表单的字段,现在我在提交表单时得到一个错误:

JForm::validateField() rule `machinename` missing. 

我最好的猜测是我在命名或文件位置上有一个错误,但我不确定,用谷歌找不到任何东西。

自己找到解决方案,似乎需要将rules文件夹路径添加到表单定义中:

<form addrulepath="/administrator/components/com_sample/models/rules">

我一直在努力解决这个问题。我认为这个错误意味着Joomla找不到规则文件,但是当我单步通过核心时,我意识到在加载规则文件后,Jommla检查规则中是否有适当命名的类。我在类名中输入了一个错别字。因此,我对任何与服务器端验证斗争的人的建议是检查规则文件是否在您期望的地方,类名是否正确。显然我知道,但我花了很长时间才明白。