如果从其他模型检索数据,验证不能在cake php中工作

时间:2012-02-28 11:11:58

标签: php cakephp cakephp-1.3

我有表“car_types”,一个Controller users_controller,模型Car_type和action url

localhost/carsdirectory/users/dashboard

dashboard.ctp(视图)

 <?php echo $this->Form->create('Users', array('type' => 'file', 'action' => 'dashboard')); ?>
 <select>
 <?php foreach($car_type as $key => $val) { ?>
 <option value="" selected="selected">select</option>
 <option value="<?php echo $val['Car_type']['id']; ?>">
 <?php echo $val['Car_type']['car_type']; ?>
 </option>
 <?php } ?>
 </select>
 <?php echo $this->Form->end(array('label' => 'Submit', 'name' => 'Submit', 'div' => array('class' => 'ls-submit')));?>

Car_type.php(模型)

 class Car_type extends AppModel
   {
   var $name = 'Car_type';

   var $validate = array(

   'car_type' => array(

       'rule' =>'notEmpty',
       'message' => 'Plz select type.'
         )
     ); 
    }

users_controller.php中(控制器)

  public function dashboard(){

      $this->loadModel('Car_type'); // your Model name => Car_type

      $this->set('car_type', $this->Car_type->find('all'));

   }

但是当我点击提交按钮时我想显示msg(Plz选择类型)而现在它不起作用我知道我的代码有问题我不能理清它所以PLZ帮助我

提前感谢,vikas tyagi

2 个答案:

答案 0 :(得分:1)

此验证规则用于验证何时添加某种车型,而不是用户。

为此,您需要在car_type_id字段的用户模型中进行验证:

class User extends AppModel {
    var $name = 'User';

    var $validate = array(
        'car_type_id' => array(
            'rule' => 'notEmpty',
            'message' => 'Please, select car type.'
        )
    );
}

你的表格:

$this->Form->input('car_type_id', array('options' => $car_type, 'empty' => '- select -'));

您的控制器可以简单地:

$this->set('car_type', $this->User->Car_type->find('all'));

但是,不知道这是否是您的整个代码,以确认这两个模型之间的关系是否正确。

答案 1 :(得分:0)

考虑到它的数据,您应该在模型中存储有效选项列表。

var $carType= array('a' => 'Honda', 'b' => 'Toyota', 'c' => 'Ford');

您可以在Controller中获取该变量:

$this->set('fieldAbcs', $this->MyModel->carType);

不幸的是,你不能简单地在inList规则的规则声明中使用该变量,因为规则被声明为实例变量,而那些只能静态初始化(不允许变量)。最好的方法是在构造函数中设置变量:

var $validate = array(
    'carType' => array(
        'allowedChoice' => array(
            'rule' => array('inList', array()),
            'message' => 'Pls select type.'
        )
    )
);

function __construct($id = false, $table = null, $ds = null) {
    parent::__construct($id, $table, $ds);

    $this->validate['carType']['allowedChoice']['rule'][1] =
    array_keys($this->fieldAbcChoices);
}