0

我正在尝试在模型中使用自定义函数实现它不起作用我没有得到我的代码有什么问题。我想稍后打电话给基本的我会提出我的条件。

这是型号代码

public function rules()
    {
        return [
            ['mobile_number', 'required'],
            ['mobile_number', 'myfunction'],

        ];
    }

public function myfunction($attribute,$params)
    {
             $this->addError($attribute, 'You have already submitted');

    }

这是控制器代码

public function actionCreate()
    {
        $model = new Createuser();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

它没有将错误分配给表单字段。

Thanks in advance.
4

5 回答 5

3

我猜mobile_number你的数据中不存在名为的参数或者它是一个空字符串,所以尝试'skipOnEmpty' => false在你的代码中添加。

无论如何,它对我有用。

public function rules()
{
    return [
        ['mobile_number', 'required', 'skipOnEmpty' => false],
        ['mobile_number', 'myfunction', 'skipOnEmpty' => false],
    ];
}
于 2019-05-17T09:17:29.513 回答
0

在你的控制器中试试这个

protected function performAjaxValidation($model = NULL) {

        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            echo json_encode(ActiveForm::validate($model));
            Yii::$app->end();
        }
    }

public function actionCreate()
{
    $model = new Createuser();
    $this->performAjaxValidation($model);
    if ($model->load(Yii::$app->request->post()) && $model->save() && $model->validate()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}
于 2015-12-03T10:15:18.843 回答
0

代码很好。动态表单验证出错。

于 2017-06-08T11:20:59.753 回答
0

你确定你没有扩展模型类吗?如果是这样,你需要把这个:

$model->validate()
于 2015-12-03T07:20:43.627 回答
0

您的型号:

public function rules()
{
    return [
        ['mobile_number', 'required'],
        ['mobile_number', 'myfunction'],
    ];
}

public function myfunction($attribute,$params)
{
    $this->addError($attribute, 'You have already submitted');
    return false;   
}

和你的控制器:

public function actionCreate()
{
    $model = new Createuser();

    if ($model->load(Yii::$app->request->post()) && $model->save() && $model->validate()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}
于 2015-12-03T07:31:28.950 回答