Ajax question

I use an update page for updating project information. On this page an username can be selected using an dropdown. See the following snipped:




<?php echo Html::activeLabel($project, 'User'); ?>

<?php echo Html::activeDropDownList($project, 'user', Html::listData(user::model()->findAll(), 'id', 'username'),



When i select an username, i want to display the realname in a additional label.

I understand this can be done using ajax.

Can anyone explain howto?

I will show you how I solved this, maybe there are some other ways too…

First in the view you have to attach the ajax call to the dropdownlist and to put some "container" where the realname will be displayed




<?php echo Html::activeLabel($project, 'User'); ?>

<?php 

echo Html::activeDropDownList($project, 'user', Html::listData(user::model()->findAll(), 'id', 'username'),

    array(

                'ajax'=>array(

                    'url'=>CController::createUrl('printName'),

                    'type'=>'POST',

                    'data'=>array(

                        'xId'=>"js:$('#MODELNAME_user').val()",

                    ),

                    'update'=>'#print',

            ),

        )); 

?>

<div id="print"></div>



‘xId’=>“js:$(’#MODELNAME_user’).val()” - xId gets the selected username ID, MODELNAME is the name of your current model, (you can look at the webpage source to see the id of the SELECT that the activeDropDownList creates.

createUrl(‘printName’) - printName is the name of the action that will return the requested username

‘update’=>’#print’ - print is the ID of the DIV where the username will be displayed

<div id="print"></div> is where the username will be displayed, with CSS you can style and possion it where needed.

in the controler

  • you have to add ‘printName’ to the accessRules according to your need (all users, only registered,…)

  • you have to add the actionPrintName




    public function actionPrintName()

    {

        //.. accept only ajax request

        if ( Yii::app()->request->isAjaxRequest)

        {

            $xId="";

            if(isset($_POST['xId'])) {

                 //.. get the selected ID, here you can add some test like if xId is only numeric etc...

                 $xId=(int)$_POST['xId'];

                 //.. find all data for the selected ID

                 $tmpUser=User::model()->findbyPk($xId);

                 //.. print the username

                 echo "$tmpUser->username";

                 Yii::app()->end();

            }

        }

        else

            throw new CHttpException(404,'Page does not exist.');

    }



Just the answer i needed. I implemented your example and it worked for me.

Thanks!