回调函数在codeigniter表单验证中运行时没有错误消息

时间:2013-04-18 21:00:42

标签: php codeigniter callback validation

抱歉我的英文不好,

我正在创建一个表单,该表单采用一些值来指定我的codeigniter项目中的报表选项。我想显示在回调函数中创建的错误消息。我有3个回调函数“ checkStartDate() checkFinishDate() checkIssueExists()”如果验证部分处理“必需”之类的错误没有设置回调,没关系。但是当我在回调函数中设置错误消息时,它们不会显示出来。重要的是; 如果“必需”规则未通过,我的所有回调错误都会显示为。但是如果“必需”条件通过,则没有错误消息。

我有错误消息的问题,回调函数正常工作。当我给出错误的值时,它们返回FALSE。

这是我的代码:

视图:

<div id="newIssue">
<p>
    Fill the form below, add your issue to searching pool.</br>
</p>    

<?php
    if( isset($_GET['validationErrors']) )
        echo $_GET['validationErrors'];
?>

<?=form_open("main/add-to-pool");?>
    <table class="form-table">
        <tr>
            <td>Issue </td>
            <td><?=form_input('issue', $this->input->post('issue'));?></td>
        </tr>

        <tr>
            <td>Report timing </td>
            <td>
                <?php
                    $options = array(
                      'daily'    => 'Every day',
                      'weekly'   => 'Every week',
                      'monthly'  => 'Every month',
                    );

                    echo form_dropdown('timing', $options, 'weekly');
                ?>
            </td>
        </tr>

        <tr>
            <td>Start Date </td>
            <td>
                <?=form_input(array('name' => 'startDate', 'type' => 'date'), $this->input->post('startDate'));?>
            </td>
        </tr>

        <tr>
            <td>Finish Date </td>
            <td>
                <?=form_input(array('name' => 'finishDate', 'type' => 'date'), $this->input->post('finishDate'));?>
            </td>
        </tr>

        <tr>
            <td>Location based </td>
            <td>&nbsp&nbsp 
                <?php
                echo form_radio(array(
                        'name'      => "location",
                        'class'     => "radio",
                        'checked'   => TRUE
                    )); 
                ?>
                Yes

                <?php
                echo form_radio(array(
                        'name'      => "location",
                        'class'     => "radio",
                        'checked'   => FALSE
                    )); 
                ?>
                No
            </td>
        </tr>

        <tr>
            <td></td>
            <td>
                <div style="float:right">
                    <?php
                    echo form_submit(array(
                            'class' => 'btn btn-info', 
                            'id'    => 'addToPool',
                            'name' => 'addToPool', 
                            'value' => 'Add to Pool'
                        ));
                    ?>
                </div>
            </td>
        </tr>
    </table>
<?=form_close();?>

控制器:

public function addToPool()
{
    $this->load->library('form_validation');

    $this->form_validation->set_rules('issue', 'Issue', 'required|trim|xss_clean|callback_checkIssueExists');
    $this->form_validation->set_rules('timing', 'Report Timing', 'required|trim|xss_clean');
    $this->form_validation->set_rules('startDate', 'Start Date', 'required|trim|xss_clean|callback_checkStartDate');
    $this->form_validation->set_rules('finishDate', 'Finish Date', 'required|trim|xss_clean|callback_checkFinishDate');

    if ($this->form_validation->run()) {
        $issueContent = preg_replace("/\s+/"," ", $this->input->post('issue') );
        $startDate = date("Y-m-d H:i:s", strtotime($this->input->post('startDate')));
        $finishDate = date("Y-m-d H:i:s", strtotime($this->input->post('finishDate')));

        $issue = new Issue();

        $issue->setContent($this->clearTurkishCharacters($issueContent));
        $issue->setTrContent($issueContent);
        $issue->setCreatedDate(date("Y-m-d H:i:s"));
        $issue->setUpdatedDate(date("Y-m-d H:i:s"));
        $issue->setStartDate($startDate);
        $issue->setFinishDate($startDate);

        $user = new User();
        $user->setUsername($this->session->userdata('username'));
        $user->dbToUser();

        $issue->setUser($user);

        if ($issue->issueToDb()) {
            $_GET['newIssueFancyBox'] = "close";

            $this->home();
        } else
            echo "An error occured while adding user to database!";

    } else {
        $_GET['validationErrors'] = validation_errors('<div class="alert alert-error">','</div>');
        $_GET['newIssueFancyBox'] = "open";

        $this->home();
    }
}

public function checkStartDate()
{
    $startDate = $this->input->post('startDate');

    if (strtotime($startDate) < strtotime('-1 day')) {
        $this->form_validation->set_message('checkStartDate', 'The %s field cannot take a value before today.');
        return FALSE;
    } else {
        return TRUE;
    }
}

public function checkFinishDate()
{
    $startDate = $this->input->post('startDate');
    $finishDate = $this->input->post('finishDate');

    if (strtotime($finishDate) < strtotime($startDate) || strtotime($finishDate) < strtotime('-1 day') ) {
        $this->form_validation->set_message('checkFinishDate', 'The %s field cannot take a value before start date.');
        return FALSE;
    } else {
        return TRUE;
    }
}

public function checkIssueExists()
{
    $this->load->model('modelIssue');

    $issueContent = preg_replace("/\s+/"," ", $this->input->post('issue') );

    $issue = new Issue();

    $issue->setContent($issueContent);

    $user = new User();
    $user->setUsername($this->session->userdata('username'));
    $user->dbToUser();

    $issue->setUser($user);

    if( $this->modelIssue->checkIssueExists($issue) ) {
        $this->form_validation->set_message('checkIssueExists', 'You have already the same issue in pool.');
        return FALSE;
    }
    else
        return TRUE;
}

2 个答案:

答案 0 :(得分:2)

您应该扩展CI_Form_validation而不是使用回调

class MY_Form_validation extends CI_Form_validation
{

    public function checkIssueExists ( $modelIssue )
    {
        // $ci =& get_instance(); //uses __get magic function instead
        //$modelIssue field is automatically passed as param, no need for $_POST

        if ( something ) {
            $this->form_validation->set_error ( 'checkIssueExists' ,
                                                'Some error' ) ;
            return false ;
        }
        else {
            return true ;
        }
    }
    /** magic function to get CI super object(object) **/
    public function __get ( $object )
    {
        $instance = &get_instance () ;
        return $instance->$object ;
    }

}

- 像其他人建议的那样使用内联错误

echo form_error('field_name')

OR

foreach( validation_errors() as $error ):
 ...
endforeach;

我还会在./config

中设置一个form_validation.php配置文件
$config = array(
    'class/method' => array(
      array('field'=>'', 'label'=>'', 'rules'=>'required|checkIssueExists'),  
    ),
);

你现在干净的控制器方法

        // If the form validation cant find any key for this class/method
        // in config/form_validation.php
        // optionally you can pass in a key
        // ie: if($this->form_validation->run('key'))
        if( !$this->form_validation->run() )
        {
            return $this->home();
        }

        //validation must have passed

答案 1 :(得分:0)

我自己已经解决了这个问题,但是根据@ Philip的回答,我已经知道在我更改代码时会发生什么。在我的旧代码中,我有回调函数,然后我将其更改为@ Philip的答案。但我仍然没有得到我想要显示的错误消息。我刚刚意识到,当我在同一个函数中创建User或Issue类对象时,我无法设置错误消息。

在我的旧代码(library / MY_Form_validation.php)中;

public function checkIssueExists()
{

    $this->load->model('modelIssue');

    $issueContent = preg_replace("/\s+/"," ", $this->input->post('issue') );

    $issue = new Issue();

    $issue->setContent($issueContent);

    $user = new User();
    $user->setUsername($this->session->userdata('username'));
    $user->dbToUser();

    $issue->setUser($user);

    if (!$this->modelIssue->checkIssueExists($issue->getContent(), $issue->getUser()->getUsername())) {
        return TRUE;
    } else {
        $this->form_validation->set_message('checkIssueExists', 'You have already the same issue in pool.');
        return FALSE;
    }
}

您可以看到$issue = new Issue();$user = new User();行导致我的问题。但我不明白为什么会这样。我有3个控制器类,

  • Main(处理请求和基本功能,如signIn(),signUp(),home(),dashboard()等。)
  • 用户(基本用户函数,如getUsername(),setId(),dbToUser(),userToDb()等。)
  • 问题(基本问题函数,如getIssue(),setUser(),getContent()等。)

我需要这些功能,所以我认为我可以在需要时使用这些类。但是在回调函数或MY_Form_validation.php文件中,我不能像上面那样使用它们。

我已经更改了我的代码(以及其他依赖于我的代码的页面),如下所示,它现在可以正常工作; 库/ MY_Form_validation.php;

public function checkIssueExists()
{
    $issueContent = preg_replace("/\s+/"," ", $this->input->post('issue') );
    $username = $this->session->userdata('username');

    if (!$this->modelIssue->checkIssueExists($issueContent, $username)) {
        return TRUE;
    } else {
        $this->form_validation->set_message('checkIssueExists', 'You have already the same issue in pool.');
        return FALSE;
    }
}

但我不知道为什么我在同一个函数中使用我的类时无法设置错误消息。

感谢您的帮助。