使用CakePHP 2.x进行HABTM表单验证 [英] HABTM form validation with CakePHP 2.x
问题描述
这是此 CakePHP中的HABTM表单验证问题的更新,因为我得到相同的问题在我的cakephp 2.7(最后cakephp 2.x现在与php 5.3支持在2016年),并找不到一个好的方法来做。
Here is an update for this HABTM form validation in CakePHP question, as I get the same problem on my cakephp 2.7 (last cakephp 2.x for now with php 5.3 support at the date of 2016) and can't find a good way to do it.
问题:
我有一个HABTM关系,例如: Post<标签
。这工作与Cakephp生成的多个复选框选择。我想为每个帖子至少有一个标签。
I have a HABTM relation like : Post <-> Tag
. This work with the multiple checkbox selection generated by Cakephp. I want to have at least one Tag for every Post.
我正在寻找最干净的方法来做到这一点。
I'm looking for the cleanest way to do this.
推荐答案
这里是我认为是最好的现在。它使用cakephp 3.x行为进行HABTM验证。
Here are what I think is the best for now. It use the cakephp 3.x behaviour for HABTM validation.
我选择只在模型中工作,使用最通用的代码。
I choose to only work in model, with the most generic code.
在 AppModel.php
中,设置 beforeValidate()
和 afterValidate()
class AppModel extends Model {
/** @var array set the behaviour to `Containable` */
public $actsAs = array('Containable');
/**
* copy the HABTM post value in the data validation scope
* from data[distantModel][distantModel] to data[model][distantModel]
* @return bool true
*/
public function beforeValidate($options = array()){
foreach (array_keys($this->hasAndBelongsToMany) as $model){
if(isset($this->data[$model][$model]))
$this->data[$this->name][$model] = $this->data[$model][$model];
}
return true;
}
/**
* delete the HABTM value of the data validation scope (undo beforeValidate())
* and add the error returned by main model in the distant HABTM model scope
* @return bool true
*/
public function afterValidate($options = array()){
foreach (array_keys($this->hasAndBelongsToMany) as $model){
unset($this->data[$this->name][$model]);
if(isset($this->validationErrors[$model]))
$this->$model->validationErrors[$model] = $this->validationErrors[$model];
}
return true;
}
}
之后,您可以在模型中使用验证像这样:
After this, you can use your validation in you model like this :
class Post extends AppModel {
public $validate = array(
// [...]
'Tag' => array(
// here we ask for min 1 tag
'rule' => array('multiple', array('min' => 1)),
'required' => true,
'message' => 'Please select at least one Tag for this Post.'
)
);
/** @var array many Post belong to many Tag */
public $hasAndBelongsToMany = array(
'Tag' => array(
// [...]
)
);
}
使用:
- Painless HABTM Validation in CakePHP by @jesal
- HABTM form validation in CakePHP
- CakePHP 2.x Saving and validating a HABTM relation example
这篇关于使用CakePHP 2.x进行HABTM表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!