まず、カスタム検証ルールを設定しますlibraries/MY_Form_validation.php
ファイルが存在しない場合は、作成します。
の内容MY_Form_validation.php
:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
function __construct($config = array())
{
parent::__construct($config);
}
function valid_num_products()
{
//Perhaps it would be better to store a maxProducts column in your users table. That way, every user can have a different max products? (just a thought). For now, let's be static.
$maxProducts = 3;
//The $this object is not available in libraries, you must request an instance of CI then, $this will be known as $CI...Yes the ampersand is correct, you want it by reference because it's huge.
$CI =& get_instance();
//Assumptions: You have stored logged in user details in the global data array & You have installed DataMapper + Set up your Product and User models.
$p = new Product();
$count = $p->where('user_id', $CI->data['user']['id'])->count();
if($count>=$maxProducts) return false;
else return true;
}
}
次に、 でルールを設定しますconfig/form_validation.php
。
form_validation.php の内容
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config = array
(
'addProduct' => array
(
array
(
'field' => 'name',
'label' => 'Product Name',
'rules' => 'required|valid_num_products'
)
)
);
次に、 でエラー メッセージを設定しますlanguage/english/form_validation_lang.php
。次の行を追加します。
$lang['valid_num_products'] = "Sorry, you have exceeded your maximum number of allowable products.";
コントローラーでは、次のようなものが必要になります。
class Products extends MY_In_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
}
function add()
{
$p = $this->input->post();
//was there even a post to the server?
if($p){
//yes there was a post to the server. run form validation.
if($this->form_validation->run('addProduct')){
//it's safe to add. grab the user, create the product and save the relationship.
$u = new User($this->data['user']['id']);
$x = new Product();
$x->name = $p['name'];
$x->save($u);
}
else{
//there was an error. should print the error message we wrote above.
echo validation_errors();
}
}
}
}
最後に、なぜ私が から継承したのか不思議に思うかもしれませんMY_In_Controller
。Phil Sturgeon がKeeping It Dryというタイトルのブログに書いた素晴らしい記事があります。この投稿で、彼はアクセス制御コントローラーから継承するコントローラーの作成方法を説明しています。このパラダイムを使用することで、から継承するコントローラーはMY_In_Controller
ログインしていると見なすことができる$this->data['user']['id']
ため、それらは利用可能であると見なされます。実際に$this->data['user']['id']
は で SET ですMY_In_Controller
。これは、コントローラーのコンストラクター、または (さらに悪いことに) それらの関数でログイン状態をチェックしないように、ロジックを分離するのに役立ちます。