atp*_*atp 5 validation cakephp drop-down-menu
我想对我的模型中的列表使用CakePHP的核心验证:
var $validate = array(
'selectBox' => array(
'allowedChoice' => array(
'rule' => array('inList', $listToCheck),
'message' => 'Enter something in listToCheck.'
)
)
);
Run Code Online (Sandbox Code Playgroud)
但是,该$listToCheck数组与视图中使用的数组相同,以填充选择框.我在哪里放这个功能?
public function getList() {
return array('hi'=>'Hello','bi'=>'Goodbye','si'=>'Salutations');
}
Run Code Online (Sandbox Code Playgroud)
已经在我的控制器中,我正在为视图设置其中一个操作,例如:
public function actionForForm() {
$options = $this->getList();
$this->set('options', $options);
}
Run Code Online (Sandbox Code Playgroud)
所以,我不想复制getList()函数...我可以把它放在哪里,所以模型可以调用它来填充它的$listToCheck数组?
谢谢你的帮助.
dec*_*eze 11
考虑到它的数据,您应该在模型中存储有效选项列表.
class MyModel extends AppModel {
var $fieldAbcChoices = array('a' => 'The A', 'b' => 'The B', 'c' => 'The C');
}
Run Code Online (Sandbox Code Playgroud)
您可以在Controller中获取该变量,如下所示:
$this->set('fieldAbcs', $this->MyModel->fieldAbcChoices);
Run Code Online (Sandbox Code Playgroud)
遗憾的是,您不能简单地在规则的规则声明中使用该变量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);
}
Run Code Online (Sandbox Code Playgroud)
如果你不熟悉覆盖构造函数,你也可以在beforeValidate()回调中执行此操作.
另请注意,您不应将字段命名为"selectBox".:)
| 归档时间: |
|
| 查看次数: |
5054 次 |
| 最近记录: |