2

特定のオブジェクトの関連アイテムを検証するための検証ルールを設定する必要があります。つまり、ユーザーはそれに関連する製品を 3 つまで持つことができます。

DataMapper は _related_max_size ルールを使用してこの検証をチェックできると思いますが、モデルの $validation 配列でそれを使用する方法がわかりません。

これまでのところ、ユーザー モデルと製品モデルの両方でこれを試しました。

var $validation = array(
    'product' => array(
         'rules' => array('max_size' => 3)
    )
);

モデル、コントローラー、そして最後にビューでこれを設定する方法の例を誰かに見せてもらえますか?

編集:私が言いたいのは、ユーザーは多くの製品を持っており、一定量の製品を作成できるということです.3つの製品としましょう。その量に達すると、ユーザーは製品を作成できなくなり、この検証ルールはユーザーを許可するべきではありませんより多くの製品を作成するために。

これは DB スキーマになります。

Users table
------------------
id   |  username  |
------------------

Products table
------------------------
id  | user_id |  name   |
------------------------

詳細はこちら: http://codeigniter.com/forums/viewthread/178045/P500/

ありがとう!

編集:

わかりました、すべてが機能するようになりました…ただし、次のことを行う必要があります。

var $validation = array(
    'product' => array(
        'label' => 'productos',
        'rules' => array('required','max_size' => $products_limit)
    )
); 

$products_limit は、ユーザーが関連付けた「プラン」から取得され、ユーザーがログインしたときにセッションに保存されます。これを実行しようとすると、次のようになります。

Parse error: syntax error, unexpected T_VARIABLE in /var/www/stocker/application/models/user.php on line 11 

この設定を動的にする方法はありますか?

4

3 に答える 3

1

モデル内

var $validation = array(
    array(
        'field' => 'username',
        'label' => 'Username',
        'rules' => array('required')
    )
);

コントローラーで。$this -> $object = new Your_model();

$object->validate();

    if ($object->valid)
    { $object->save();

        // Validation Passed
    }
    else
    { $data['error'] = $object->error;
        // Validation Failed
    }

ビューで。

echo $error->field_name
于 2012-02-23T11:34:20.660 に答える
0

これまで Codeigniter を使用したことはありませんが、お手伝いできる機会をください。これまでのところ、Code-igniter に組み込みの検証は見つかりませんでした (間違っていたら訂正してください)。

私が考えることができる1つの回避策は、Callback:Your own Validation Functionsです。以下、切り抜きです。ご希望どおりにならなかった場合はご容赦ください。

モデル内: (次のようなものを作成)

function product_limit($id)
{
    $this->db->where('product_id',$id);
    $query = $this->db->get('products');
    if ($query->num_rows() > 3){
        return true;
    }
    else{
        return false;
    }
}

コントローラ内: (次のようなものを作成)

function productkey_limit($id)
{
    $this->product_model->product_exists($id);
}

public function index()
{
    $this->form_validation->set_rules('username', 'Username', 'callback_product_limit');
}

詳細については、より完全なマニュアル ページを参照してください。CodeIgniter も初めてです。しかし、これがあなたを複雑にするのではなく、あなたを助けることを願っています.

于 2012-02-19T13:06:30.557 に答える
0

まず、カスタム検証ルールを設定します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_ControllerPhil Sturgeon がKeeping It Dryというタイトルのブログに書いた素晴らしい記事があります。この投稿で、彼はアクセス制御コントローラーから継承するコントローラーの作成方法を説明しています。このパラダイムを使用することで、から継承するコントローラーはMY_In_Controllerログインしていると見なすことができる$this->data['user']['id']ため、それらは利用可能であると見なされます。実際に$this->data['user']['id']は で SET ですMY_In_Controller。これは、コントローラーのコンストラクター、または (さらに悪いことに) それらの関数でログイン状態をチェックしないように、ロジックを分離するのに役立ちます。

于 2012-02-21T15:11:50.810 に答える