Dynamically Show Required Textfield Depending On Dropdownlist Value

Good day. My problem is I have a dropDownlist with three options: A, B, C. What I need to do is to show a textfield depending on what the user chose.

Example: user chose A => it will show textfield AA (which should be required and not empty)

     user chose B => it will show textfield BB (which should be required and not empty)


     user chose C => it will show textfield CC (which should be required and not empty)

Can anyone please help me? Thank you.

http://www.yiiframework.com/wiki/24/

They are two dropdownlists. What I need is one dropdownlist, and three hidden textfields. Depending on the value chosen on the dropdownlist, it should show one hidden textfield and make it a required input for the user.

i did it in my project. I used below method

In my view, I used jquery validation before submit the form.

In my controller, I used scenario concept. Based on my input selection, I will apply different scenario

Ex

if($model->choice==‘A’)

$model->scenario=‘A’;

else if($model->choice==‘B’)

$model->scenario=‘B’;

Try this

Where in the javascript can I put that scenario? Cause it should dynamically change right on the form. I mean I can’t submit it yet. It has to show right after I choose from the dropdownlist.

Add scenario in controller[Just read about scenario concept][Server side validation].

I think, We can’t change different validation dynamically using model without page refresh. Try the normal validation in js[client side validation].

Can you please elaborate? I didn’t understand.I’m sorry I’m new here. I do know how to set the scenario but how can I set the scenario in the controller if I have to check the scenario BEFORE it submits the form and go to the controller?

Here’s what happens.

a) user can choose from the dropdownList. Possible values are A, B, C.

B) if user chooses A, it will show textfield AA. if user chooses B, it will show textfield BB. if user chooses C, it will show textfield CC.

c) The textfield that will show, which is dependent on the dropdownlist value that the user will choose, should not be empty.

My problem is how can I validate if the textfield chosen is not empty? I cannot declare on the rules that textfields AA, BB, CC should be required because this ‘required’ rule is still dependent on the value of the dropdownlist. If I set a scenario on the controller, then it will submit the form immediately and we don’t want that because it needs to validate that the textfield that appeared depending on the dropdownlist value that the user has chosen should be required.

Is there even a way to do this?

Okay I already found a way to solve it. Thanks to this post

The only problem now is when an I leave the chosen textfield as blank and it shows the error, the textfield that was shown (the one which is dependent on the value of dropdownlist) disappears or goes back to state display:hidden. This happens right after the ‘textfield cannot be blank’ error message. The initial chosen value of dropdownList is still there and is still on focus but the textfield disappears.

View:

<div class="row">

	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'org_type'); ?&gt;


	&lt;?php echo &#036;form-&gt;dropDownList(&#036;model,'org_type', &#036;model::getOrgType(), array('prompt'=&gt;'', 'id'=&gt;'orgType')); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'org_type'); ?&gt;


&lt;/div&gt;





&lt;div class=&quot;row&quot; style=&quot;display:none&quot; id=&quot;sec&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'sec_ref'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'sec_ref', array('id'=&gt;'secField')); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'sec_ref'); ?&gt;


&lt;/div&gt;





&lt;div class=&quot;row&quot; style=&quot;display:none&quot; id=&quot;dti&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'dti_ref'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'dti_ref', array('id'=&gt;'dtiField')); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'dti_ref'); ?&gt;


&lt;/div&gt;





&lt;div class=&quot;row&quot; style=&quot;display:none&quot; id=&quot;cda&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'cda_ref'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'cda_ref', array('id'=&gt;'cdaField')); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'cda_ref'); ?&gt;


&lt;/div&gt;

Model:

public function addCustomError($attribute, $error) {

    &#036;this-&gt;customErrors[] = array(&#036;attribute, &#036;error);


}





/**


 */


protected function beforeValidate() {


    &#036;r = parent::beforeValidate();


	


	if (&#036;this-&gt;org_type == 'Single') {//this is the checkbox





        &#036;this-&gt;validatorList-&gt;add(CValidator::createValidator('required',&#036;this,'dti_ref',array()));


   


    }





	if (&#036;this-&gt;org_type == 'Partnership') {//this is the checkbox





        &#036;this-&gt;validatorList-&gt;add(CValidator::createValidator('required',&#036;this,'sec_ref',array()));


   


    }


    


    if (&#036;this-&gt;org_type == 'Corporation') {//this is the checkbox





        &#036;this-&gt;validatorList-&gt;add(CValidator::createValidator('required',&#036;this,'sec_ref',array()));





    }


    


    if (&#036;this-&gt;org_type == 'Cooperative') {//this is the checkbox





        &#036;this-&gt;validatorList-&gt;add(CValidator::createValidator('required',&#036;this,'cda_ref',array()));





    }


    foreach (&#036;this-&gt;customErrors as &#036;param) {


        &#036;this-&gt;addError(&#036;param[0], &#036;param[1]);


    }


    return &#036;r;


}

javascript on the view:

<?php

/* @var $this BusinessController */

/* @var $model Business */

/* @var $form CActiveForm */

Yii::app()->clientScript->registerScript(‘orgType’, "

$(’#orgType’).change(function(){

if(&#036;('#orgType').val() == 'Single')


{


	&#036;('#dti').show();


	&#036;('#dtiField').addClass('required');


	&#036;('#cda').hide();


	&#036;('#sec').hide();





}


if((&#036;('#orgType').val() == 'Partnership') || (&#036;('#orgType').val() == 'Corporation'))


{


	&#036;('#sec').show();


	&#036;('#secField').addClass('required');


	&#036;('#dti').hide();


	&#036;('#cda').hide();


}


if(&#036;('#orgType').val() == 'Cooperative')


{


	&#036;('#cda').show();


	&#036;('#cdaField').addClass('required');


	&#036;('#dti').hide();


	&#036;('#sec').hide();


}


return false;

});

");

?>

Sure we can, just not with scenarios. We just need a dynamic custom validator.

Here’s a basic example of how it would work. No promises that this actually runs, just that it gets my point across:




class Model {

	...

	/**

	 * @return array model validation rules

	 **/

	public function rules() {

		return array(

			array('control_field', 'required', 'on' =>'scenario'),

			array('dep_field_1', 'validateDependentField', 'on' =>'scenario',

				'controlAttributeName'  =>'control_field',

				'controlAttributeValue' =>'someValue',

				'rules'                 =>array('required'),

				'unsetIfNotSelected'    =>true,

			),

			array('dep_field_2', 'validateDependentField', 'on' =>'scenario',

				'controlAttributeName'  =>'control_field',

				'controlAttributeValue' =>'someOtherValue',

				'rules'                 =>array('required'),

				'unsetIfNotSelected'    =>true,

			),

		);

	}


	/**

	 * Validate a field based on the value of another field.

	 **/

	public function validateDependentField($attribute, $params) {

		// Skip validation when there are already errors

		if ($this->hasErrors()) {

			return;

		}

		// Skip validation if this attribute isn't selected by the

		// control field.

		elseif ($this->$params['controlAttributeName']!=$params['controlAttributeValue']) {

			if ($params['unsetIfNotSelected']) {

				unset($this->$attribute);

			}

			return;

		}

		// Apply validator rules. 

		else {

			foreach ($params['rules'] as $validatorName =>$params) {

				$validatorName = !is_numeric($validatorName) ? $validatorName : $params;

				$params        =  is_array($params)          ? $params        : array();

				$this->validatorList->add(CValidator::createValidator($validatorName,$this,$attribute,$params));

			}

		}

	}

	...

}