2

对不起,我的英语不好,

我正在创建一个表单,它采用一些值来指定我的 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;
}
4

2 回答 2

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')

或者

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
于 2013-04-19T11:51:35.570 回答
0

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

在我的旧代码中(库/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;
    }
}

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

谢谢你的帮助。

于 2013-04-21T13:06:25.277 回答