我有一个表"car_types",一个Controller users_Controller,型号car_type和动作url
localhost/carsdirectory/users/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'));
}
但是当我点击提交按钮时,我想显示消息(Plz选择类型),现在它不起作用,我知道我的代码有问题,我无法解决它,所以请帮助我
提前感谢,vikas tyagi
此验证规则用于在添加某些车型时进行验证,而不是用户。
为此,您需要从car_type_id字段在User model中进行验证:
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'));
但是,不知道这是否是您确认这两个模型之间关系正确的完整代码。
考虑到这是数据,您应该在模型中存储有效选择的列表。
var $carType= array('a' => 'Honda', 'b' => 'Toyota', 'c' => 'Ford');
您可以在控制器中获得该变量,如下所示:
$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);
}