I want to hide or display a form element based on input from another form element. Can someone help with advice?
I tried to set a _form element css style=display:hidden or style=display:block depending on the value selected in another dropdown
on the same _form using AJAX .
I tried a bunch of things but not getting anywhere. At the moment, I am consistently getting the "Bad AJAX" alert from my _form .
Hope someone can help. here is my code:
model:
...
// Perspective of:
// defendant (creditor) or plaintiff (Trustee)
// defaults to creditor.
const PERSPECTIVE_CREDITOR=0;
const PERSPECTIVE_TRUSTEE=1;
....
_form:
...
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'pcase-form',
//'enableAjaxValidation'=>false,
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnChange'=>true,
'validateOnSubmit'=>false,
'validateOnType'=>false,
),
)); ?>
....
<div class="row">
<?php echo $form->labelEx($model,'perspective_id'); ?>
<?php echo
$form->dropDownList(
$model,
'perspective_id',
$model->getPerspectiveOptions(),
array('onchange' => CHtml::ajax(array(
'type'=>'POST',
'url'=>CController::createUrl('pcase/perspectiveChanged'),
//'datatype'=>'text',
'data'=>array('perspective_id' => 'js:this.value'),
'success' => 'function(retval){$("#insider_div").attr("style",retval);}',
'error'=> 'function(){alert(\'Bad AJAX\');}',
//'update'=>'#insider_div',
)))
);
?>
<?php echo $form->error($model,'perspective_id'); ?>
</div>
<!-- insider_id is only applicable in from the creditor perspective -->
<!-- need to figure out how to set the value to NO in the dropdown and hide the dropdown if not creditor -->
<div id="insider_div">
<?php //if($model->perspective_id===PCase::PERSPECTIVE_CREDITOR): ?>
<div class="row">
<?php echo $form->labelEx($model,'insider_id'); ?>
<?php echo $form->dropDownList($model,'insider_id', $model->getInsiderOptions()); ?>
<?php echo $form->error($model,'insider_id'); ?>
</div>
<?php //endif; ?>
</div>
<!-- end of insider_div -->
....
Controller:
...
public function accessRules()
{
return array(
...
array('allow', // allow authenticated user to perform AJAX validation actions, called from _form
'actions'=>array('perspectiveChanged'),
'users'=>array('@'),
),
...
}
...
public function actionPerspectiveChanged()
{
//Handler for _form updates when perspective_id is changed.
if (Yii::app()->request->isAjaxRequest)
{
/* DID NOT WORK
echo '<div class="row">';
echo CHtml::activeLabelEx($model,'insider_id');
echo CHtml::activedropDownList($model,'insider_id', $model->getInsiderOptions());
echo '</div>';
*/
// DID NOT WORK - Try again..
//pick off the parameter value
$perspective_id = Yii::app()->request->getParam( 'perspective_id' );
if($perspective_id === PCase::PERSPECTIVE_TRUSTEE)
{
//we are going to hide the insider_id field on _form.
//by changing the style attribute on the form block div.
echo "display:none";
Yii::app()->end();
}
else
{
//display the insider_id field block on _form
echo "display:block";
Yii::app()->end();
}
}
}