Yii2-返回验证错误为json_encode

时间:2019-01-08 19:26:28

标签: php yii2

我需要一些指导,以了解如何从多个模型中收集验证错误,如果有任何错误,应将它们作为json_encode返回。我已经尝试了以下方法,但是它进入了调试器,在调试器中我可以看到错误(原因),我不理解为什么不处理并返回错误。

这是我控制器的相关部分。

$validClient = $model->validate();
if (! $validClient) {
    $flashMsg = '<strong>Client Model Not Valid!</strong>';
    $jsonMsg = implode("Client: ", $model->errors);
}
// Validate the Contacts Model
$validContacts = Model::validateMultiple($modelsContacts);
if (! $validContacts) {
    $flashMsg .= '<strong>Contacts Model Not Valid!</strong>';
    $jsonMsg .= implode("Contacts: ", $modelsContacts->errors); 
}
// Validate the Price List Model
$validPrices = Model::validateMultiple($modelsPrices);
if (! $validPrices) {
    $flashMsg .= '<strong>Price List Model Not Valid!</strong>';
    $jsonMsg .= implode("Price List: ", $modelsPrices->errors);
}

$valid = $validClient && $validContacts && $validPrices;
if ($valid) {
    //proceed with the transaction
} else {
    Yii::$app->session->setFlash('error', $flashMsg);
    echo json_encode(['status' => 'Error', 'message' => $jsonMsg]);
}

问题与未填写必填字段有关,这很好,但我只是不明白我所缺少的内容,因此它会被静静地处理并返回json字符串,而不是像现在那样错误地处理

1 个答案:

答案 0 :(得分:0)

似乎您正在尝试使用(CurrencyCode)的值更新一条记录,该记录受到数据库的约束,因为clients表将该记录称为外键。

确保CurrencyCode作为合法值传递,并且作为外键存在。

此错误是由数据库连接引发的,而不是通过在Yii中验证模型引起的。