Validation 用数组验证CakePHP模型
我想对模型中的列表使用CakePHP的核心验证:Validation 用数组验证CakePHP模型,validation,cakephp,drop-down-menu,Validation,Cakephp,Drop Down Menu,我想对模型中的列表使用CakePHP的核心验证: var $validate = array( 'selectBox' => array( 'allowedChoice' => array( 'rule' => array('inList', $listToCheck), 'message' => 'Enter something in listToCheck.' ) ) ); 但是,$listToCheck数组与
var $validate = array(
'selectBox' => array(
'allowedChoice' => array(
'rule' => array('inList', $listToCheck),
'message' => 'Enter something in listToCheck.'
)
)
);
但是,$listToCheck
数组与视图中用于填充选择框的数组相同。我应该把这个函数放在哪里
public function getList() {
return array('hi'=>'Hello','bi'=>'Goodbye','si'=>'Salutations');
}
已经在我的控制器中,在我为视图设置的一个操作中,例如:
public function actionForForm() {
$options = $this->getList();
$this->set('options', $options);
}
因此,我不想复制getList()
函数……我可以把它放在哪里,以便模型可以调用它来填充它的$listToCheck
数组
谢谢您的帮助。考虑到它是数据,您应该将有效选项列表存储在模型中
class MyModel extends AppModel {
var $fieldAbcChoices = array('a' => 'The A', 'b' => 'The B', 'c' => 'The C');
}
您可以在控制器中获得该变量,如下所示:
$this->set('fieldAbcs', $this->MyModel->fieldAbcChoices);
不幸的是,您不能在inList
规则的规则声明中简单地使用该变量,因为规则被声明为实例变量,并且这些变量只能静态初始化(不允许使用变量)。最好的解决方法是在构造函数中设置变量:
var $validate = array(
'fieldAbc' => array(
'allowedChoice' => array(
'rule' => array('inList', array()),
'message' => 'Enter something in listToCheck.'
)
)
);
function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->validate['fieldAbc']['allowedChoice']['rule'][1] = array_keys($this->fieldAbcChoices);
}
如果您不习惯重写构造函数,也可以在beforeValidate()
回调中执行此操作
还请注意,您不应将字段命名为“selectBox”。:) 谢谢你的回复。但是,如果我想在字段ABC值上使用
\uuuu()
函数,那么会发生什么?然后在构造函数中创建整个数组,或者array\u遍历它并在消息
字段上应用该函数<代码>$this->choices=array('a'=>u u('a',true),…)代码>完美。谢谢你的帮助!