Rules() ->Required

Всем добрый день. Есть две формы - одна с полями name, email, comment и вторая с полем comment, первую отдаем гостю, вторую пользователю который авторизирован. В модели обычная проверка на заполение:


public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('username, comment, email', 'required')

                );

	}




Вопрос, как сделать проверку required только для гостей, т.е. что-то вроде


public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

                        //разумеется данный вариант не работает <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/sad.gif' class='bbc_emoticon' alt=':(' />

			array('username, comment, email', 'required', 'on'=> Yii::app()->user->isGuest)

                );

	}




Возможно кому-то пригодится, вроде работает:




public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		if(Yii::app()->user->isGuest){

		return array(			

			array('name, email, comment', 'required'),

			array('email', 'email', 'message'=>'Неверный формат E-mail адреса'),

			array('name, email, comment', 'safe'),

			array('news_id, approved', 'numerical', 'integerOnly'=>true),

			array('name', 'length', 'max'=>50),

			array('email', 'length', 'max'=>100),

			array('comment', 'length', 'max'=>250),

			// The following rule is used by search().

			// @todo Please remove those attributes that should not be searched.

			array('id, news_id, approved, name, email, comment', 'safe', 'on'=>'search'),

		);

		}else{

		return array(			

			array('comment', 'required'),

			array('comment', 'safe'),

			array('news_id, approved', 'numerical', 'integerOnly'=>true),

			array('name', 'length', 'max'=>50),

			array('email', 'length', 'max'=>100),

			array('comment', 'length', 'max'=>250),

			// The following rule is used by search().

			// @todo Please remove those attributes that should not be searched.

			array('id, news_id, approved, name, email, comment', 'safe', 'on'=>'search'),

		);

	}

	}



Ссылка на оригинал http://www.yiiframework.com/forum/index.php/topic/44206-how-to-apply-validation-rules-only-when-user-is-guest/

Я бы делал проверку в контролере примерно следующим образом:




$model = new Comment();

if(Yii::app()->user->isGuest) {

    $model->scenario = 'guest';

}



в моделе:




return array(

    array('username, comment, email', 'required', 'on'=> 'guest');

);



так как держать логику в моделях по понятиям MVC - плохой тон.

Почему вы не пользуетесь сценариями?

Спасибо, исправил :)

Спасибо, уже подсказали, теперь буду пользоваться :)

Всем спасибо, тему можно закрывать ::)