Regarding Model's Scenario

Hi everyone,

Me again. I currently faced with problem on “scenario” property of a model. The problem is, I have a radio button list with two items “text” and “number”. Below this radio button list, I defined three keyword textfields. Now I’m using JQuery to hide/show those keyword textfield (When users selected “number” item in the radio button list, those keyword textfields are hidden.) What I’m trying to do now is to add server-side validation on an “answer” textfield. If users are selected “number” item in the radio button list, the answer must be numerical.

My current plan is to specify the scenario property of the model in the JQuery part as follow:

<script type="text/javascript">

$(document).ready(function(){

$("#Task_0_answer_type_0").click(function () {

  if (&#036;(this).is(&quot;:checked&quot;)){


	&#036;(&quot;.keyword&quot;).show();


	[color=&quot;#FF0000&quot;]&lt;?php &#036;task-&gt;scenario = ''?&gt;[/color]


	


  }

});

$("#Task_0_answer_type_1").click(function () {

  if (&#036;(this).is(&quot;:checked&quot;)){


	&#036;(&quot;.keyword&quot;).hide();


	[color=&quot;#FF0000&quot;]&lt;?php &#036;task-&gt;scenario = 'number'?&gt;[/color]


  }

});

});

</script>

Then I changed the rules() in the model by adding the following statement:

array(‘answer’, ‘numerical’, ‘on’=> ‘number’),

However, it does not work at all? Please help me out.

Thank you in advance.

Hi

I like your idea of using scenarios, but I don’t think you can change the scenario on the client with jquery. I think the scenario must be changed on the server with php.

I would try this in my controller action:


$model = new myModel(); /* no scenario yet */

$model->unsetAttributes();


/* Test if data was received from client */

if(isset($_POST[$myModel]))

{

     /* Test what data is in radio button */

     if(...

          $model->scenario = 'bla';

     ...

          $model->scenario = 'foo';


     /* Mass assign model's data */

     $model->attributes=$_POST[$myModel];


     /* Validate and save the record, using the new scenario's rules */

     if($model->save())

     ...


     /* Exit */

     ...

}


/* Render */

....

If you don’t want to do the testing in your controller action, you should be able to do it in the model’s beforeValidate() function.

Tip: Use your own scenario names. Don’t use default names like ‘create’ and ‘update’.

Regards