2

我需要设置验证规则来验证特定对象上的相关项目,即:一个用户与其相关的产品不能超过 3 个。

我相信 DataMapper 可以使用 _related_max_size 规则检查此验证,但我无法弄清楚如何在模型中的 $validation 数组上使用它。

到目前为止,我已经在我的用户和产品模型中尝试过这个:

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

有人可以向我展示如何在模型、控制器和最终视图上设置它的示例吗?

编辑:我的意思是,一个用户有很多产品,并且可以创建一定数量的产品,比如说 3 个产品,当达到这个数量时,用户不能再创建产品,这个验证规则不应该允许用户创造更多的产品。

这将是数据库架构:

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

首先,在中设置自定义验证规则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. 这可以帮助您以这样一种方式分离您的逻辑,即您不会在控制器的构造函数中检查登录状态,或者(甚至更糟)在它们的功能中。

于 2012-02-21T15:11:50.810 回答
0

我以前从未使用过 Codeigniter,但请给我一个机会来帮助你。到目前为止,我没有在 Code-igniter 中找到任何内置验证(如果我错了,请纠正我)。

我能想到的一种解决方法是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 回答