开发者

Where to organize form code in Codeigniter framework

开发者 https://www.devze.com 2023-02-01 20:13 出处:网络
I\'ve read that in Codeigniter I should be organizing my form code by placing validation code into my controller and validation rules/defaults into my model.

I've read that in Codeigniter I should be organizing my form code by placing validation code into my controller and validation rules/defaults into my model.

Is this done simply by creating a function in my model like the ones below, and then calling them from inside my controller? It certainly keeps the controller clean but I want to make sure this is the proper way to organize things.

//inside widget_model.php

function myRules()
{
    $this->form_validation->set_rules('item_name', 'name', 'required');
    $this->form_validation->set_rules('item_description', 'description', 'required');
}


function myDefaults()
{
    return $defaults = array(
        'page_title' => "Add new widget",
        'fname' => 'widget_name',
开发者_如何学JAVA        'fdescription' => 'widget_description'
    );
}


You don't need to do that IMHO. The best way is to set the validation rules in your controller like this:

$this->load->helper(array('form', 'url'));

$this->load->library('validation');

$rules['username']  = "required";
$rules['password']  = "required";
$rules['passconf']  = "required";
$rules['email']     = "required";

$this->validation->set_rules($rules);

$fields['username'] = 'Username';
$fields['password'] = 'Password';
$fields['passconf'] = 'Password Confirmation';
$fields['email']    = 'Email Address';

$this->validation->set_fields($fields);

if ($this->validation->run() == FALSE)
{
    $this->load->view('myform');
}
else
{
    $this->load->view('formsuccess');
}

}

You don't need to put anything in your Model.

More on the subject here: http://codeigniter.com/user_guide/libraries/validation.html


Another option would be placing your validation rules in a config file ordered by set. CI will load these automatically (if named correctly).

0

精彩评论

暂无评论...
验证码 换一张
取 消