[英]Count total number of records in the view in yii
這是我的看法。 我上傳了記錄,如果記錄沒有成功上傳,則會出現錯誤。 我試圖獲取可以正常工作的記錄總數,但是當我嘗試獲取“有錯誤的記錄總數”時,它本身給出了“錯誤的總數”。 如何只計算“有錯誤的記錄”而不是“錯誤數”本身?
$records = 0;
$errors = 0;
/* @var array $data */
foreach ($data as $result) {
$records++;
foreach ($result["model"]->getErrors() as $attribute => $errors) {
$errors++;
}
}
每當控制器中的驗證失敗時,只需保持計數即可。 您的問題和代碼示例似乎並不完整,所以我只能猜測您真正想做什么
$errorCount = 0;
if ($_POST['data']) {
foreach ($_POST['data'] as $data) {
// create a model (let's use $model for example) out of data received + other pre-validation work
if ($model->validate) {
// post validation work, then save
$model->save(false);
} else {
$errorCount++;
}
}
}
您可以使用模型的validate()
方法。 嘗試這個。 希望這對您有所幫助。
/* @var array $data */
$allRecords = count($data);
$recordsWithErrors = 0;
foreach ($data as $result) {
if (!$result['model']->validate()) {
$recordsWithErrors++;
}
}
首先,在您的控制器中執行此操作。
public function actionCreate(){
// your code there
$records_with_errors = 0;
foreach ($data as $result) {
// assumed that you validate models before count
if ($result['model']->hasErrors()) {
$records_with_errors++;
}
}
$this->render('create', [
'records_with_errors' => $records_with_errors
]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.