Reputation: 59
I have one table, which i have divided in two section for each i have mention two action under controller, i wanted to separate validation rule for both action, so i don't want use common model rule.
Is there any way by which i can write rule in action.
I have user controller there i have defined two action called frontuser
and backenduser
.
my action in controller
public function actionfrontuserCreate()
{
// want to write rule here
}
public function actionbackenduserCreate()
{
// want to write rule here
}
Thanks
Upvotes: 0
Views: 214
Reputation: 792
Validation rules go in the model not in the controller. What you want to do is use scenarios. When you put a rules in the model you can do something like:
array('username', 'required', 'on'=>'frontUserCreate'),
By using the 'on'=>'...' part you can tell in what scenario the rule must be applied. In your controller when you create a new model you should give the scenario as a parameter:
public function actionfrontuserCreate()
{
$model = new User('frontUserCreate');
if (isset($_POST['User']) {
....
}
$this->render('viewname', array('model'=>$model));
}
Upvotes: 1
Reputation: 770
Hi i hope i can help you:
rules should be declared in the model even if the model is shared between one or more controllers with different kind of actions ...
but you do not want a rule to be executed in all of those actions so you specify wich actions can take that rule using scenarios, i leave you an example:
array('password_repeat', 'required', 'on'=>'register'),
code above only makes pasword_repeat required on scenario register
then in your controller you will specify wich scenario will be used...
$modelA = User::model()->findByPk(1); // $model->scenario = 'update'
$modelB = new User(); // $model->scenario = 'insert'
$modelB->scenario = 'light'; // custom scenario
if ($modelB->validate()) { ...
i hope this solve your issue, for bonus i suggest to check default yii scenarios insert, update, delete ....
Upvotes: 1