Yii2:我可以创建删除模型时应用的规则和自定义错误消息吗?

问题描述 投票:2回答:2

我想删除一个模型,但是当它禁止我这样做时,它可能在另一个模型中有相关记录。如何最好地使用已定义的关系来检查删除是否成功?可能还存在不允许删除的非关系原因。

一旦我确定了我的错误消息,我怎样才能最好地存储它们并将它们传递给前端? beforeDelete()只返回true或false但我当然需要向用户提供友好的错误消息,说明为什么记录无法删除...

已定义的关系例如是:

public function getPhonenumbers() {
    return $this->hasMany(Phonenumber::class, ['ph_contactID' => 'contactID']);
}
php yii2 delete-row yii2-model
2个回答
1
投票

从@vishuB和@ rob006的答案中我得到了提出我自己的解决方案的想法,我认为这将是优越的,因为我可以提供多个错误消息,它也可以在API中使用,并且它不依赖于尝试/捕获异常:

public function beforeDelete() {
    if (!parent::beforeDelete()) {
        $this->addError('contactID', 'For some unknown reason we could not delete this record.');
    }

    if (!empty($this->phonenumbers)) {
        $this->addError('contactID', 'Contact is linked to a used phone number and cannot be deleted.');
    }

    if ($some_other_validation_fails) {
        $this->addError('contactID', 'Contact cannot be deleted because it is more than two months old.');
    }

    return ($this->hasErrors() ? false : true);
}

然后在我的行动中我这样做:

$contact = Contact::findOne($contactID);
if (!$contact->delete()) {
    return $contact->getErrors();  //or use flash messages and redirect to page if you prefer
}
return true;

1
投票

您可以在beforeDelete()中抛出异常并显示错误消息,并在控制器中捕获它。

public function beforeDelete() {
    if ($this->getPhonenumbers()->exist()) {
        throw new DeleteFailException('Records with phone numbers cannot be deleted.');
    }

    return parent::beforeDelete();
}

在控制器动作中:

try {
    $model->delete();
} catch (DeleteFailException $esception) {
    Yii::$app->session->setFlash('error', $exception->getMessage());
}
© www.soinside.com 2019 - 2024. All rights reserved.