我正在为给定方案创建验证数据的函数,但它不起作用。 型号代码:
public function rules()
{
return [
// ['session_key','deal_id','required'],
['data', 'validateCart'],
[['session_key','deal_id'], 'safe'],
// [['cartfood','session_key'], 'required','on'=>'sessionapi'],
['cartfood', 'myvalidation', 'on' => 'sessionapi'],
];
}
public function myvalidation($attribute, $params){
if (!$this->hasErrors()) {
echo '<pre>'; print_r($params); die;
}
}
控制器:代码
public function actionPayinapp(){
$data=Yii::$app->getRequest()->getBodyParams();
$cart=json_decode($data['cartfood']);
$model=new Cart();
$model->scenario = 'sessionapi';
$dataarr = array();
$model->data = $cart;
if($model->validate())
{
die(ok);
}
}
我希望myvalidation
在sessionapi
方案上运行,但它无效。
答案 0 :(得分:2)
将您的控制器代码更改为: - SkipOnEmpty
public function rules()
{
return [
// ['session_key','deal_id','required'],
['data', 'validateCart'],
[['session_key','deal_id'], 'safe'],
// [['cartfood','session_key'], 'required','on'=>'sessionapi'],
//you have to apply skipOnEmpty in your rules as
['cartfood', 'myvalidation', 'on' => 'sessionapi' ,'skipOnEmpty' => false],
];
}
public function myvalidation($attribute, $params){
if (!$this->hasErrors()) {
echo '<pre>'; print_r($params); die;
}
}