我正在使用PHP Yii框架创建一个推荐控制器,使用启发式概念。我的建议仅在用户或具有相同课程的其他用户进行预订时才有效。但是现在如果我的预订等于null,它会显示如下错误消息:
错误500为foreach()提供的参数无效
因此,我创造了一个条件,我创建了自己的信息:
我们很遗憾目前暂无图书推荐
它正在发挥作用。不幸的是,它还与错误消息一起显示。我只想展示自己的信息。以下是我的代码:
//recommendation - use heuristic concept, more accurate result as more people same course recommendation
public function actionRecommendation() {
$user = User::model()->findByPk(Yii::app()->user->id);
//get course mates
$courseMates = User::model()->findAllByAttributes(array('course_id' => $user->course_id));
$popularity = array();
if($bookings==null){Yii::app()->user->setFlash('success', 'We are sorry currently there are no recommendation of books at this moment'); }
foreach ($courseMates as $courseMate) {
//identify all bookings made by user
$bookings = Booking::model()->findAllByAttributes(array('user_id' => $courseMate->id));
foreach ($bookings as $booking) {
//add hit into array as per book
$popularity[$booking->book_id] = (isset($popularity[$booking->book_id])) ? $popularity[$booking->book_id] + 1 : 1;
}
}
//sort according to popular count
arsort($popularity, SORT_NUMERIC);
$display = 10;
foreach ($popularity as $bookId => $popular) {
//if display is 0, break the foreach, only display up 10
if ($display == 0) {
break;
}
//create book object array
$books[] = Book::model()->findByPk($bookId);
//reduce book count
$display--;
}
$this->render('recommendation',array(
'books'=>$books,
));
}()
如何修改它以便只显示自定义错误消息?
答案 0 :(得分:0)
输入字段 * 在您的模型中 *
array('gender','required','message'=>'Please select gender.'),
或者也可以调用函数。
array('gender', 'ownFunction'),
public function ownFunction() {
{
if (empty($this->gender))
$this->addError("gender", 'Please select gender.');
}
}
使用此功能,您可以在输入字段上显示自定义错误消息
错误页面
错误页面中的自定义消息。
在您的控制器中
if(Your Condition)
{
//Show Error form.
throw new CHttpException(500,'We are sorry currently there are no recommendation of books at this moment. ');
}
else
{
/* rest of code goes Here */
}
希望这有助于你