Saving The Value Of An Array Instead Of Its Index No.

I have implemented a dependent dropdown in my yii app. It works out fine, but what I want is instead of showing the index no. of an array, I want to show its actual value. Just need a suggestion because I am really a newbie here. Thank you.

This is my view forms:

<div class="row">

	<?php echo $form->labelEx($model, 'class_id'); ?>


			$category = CHtml::listData(Category::model()->findAll(array('order' => 'id')), 'id', 'category_name');

			echo $form->dropDownList($model, 'category_id',  

			$category, array(

				'prompt' => '',

				'ajax' => array(

					'type' => 'POST',

					'url' => CController::createUrl('PurchaseRequest/classifications'),

					'update' => '#'.Chtml::activeId($model,'class_id'),





	<?php echo $form->dropDownList($model, 'class_id', array(), array('style' => 'width:414px;')); ?>

	<?php echo $form->error($model, 'class_id'); ?>


And this is my controller:

public function actionClassifications() {

	$classification = Classification::model()->findAll('category_id=:category_id', array(':category_id' => (int) $_POST['PurchaseRequest']['category_id']));

	$return = CHtml::listData($classification, 'id', 'class_name');

		foreach ($return as $classificationId => $classificationName) {

			echo CHtml::tag('option', array('value' => $classificationId), CHtml::encode($classificationName), true);



Are you referring to the array passed to dropdown?

$category = CHtml::listData(Category::model()->findAll(array('order' => 'id')), 'id', 'category_name');

if you want the display and value to be the same you can do it like this:

$category = CHtml::listData(Category::model()->findAll(array('order' => 'id')), 'id', 'id');


$category = CHtml::listData(Category::model()->findAll(array('order' => 'id')), 'category_name', 'category_name');

Thank you for your answer. Ahm, what I really want is that it should save into db the value of the index instead of the index no. itself.

Ex. If I have an array of colors (red, blue, green) and I choose red, it should display red in view and in db instead of [0]<-- index of the array.

Thank you.

Sorry Mr. Right, Not so right this time. CListData returns an associative array with, in the case of models, the first attribute as the index the second as the value. When dropDownList creates the ‘dropdown’ it will generate the option tag as:<option value=“index”>value</option>.

Maybe this is better: given $ary=array(0=>‘Red’, 1=>‘Blue’, 3=>‘Green’);

<select .......>

  <option value='1'>Red</option>

  <option value='2'>Blue</option>

  <option value='3'>Green</option>


Red Blue Green should be displayed in the dropdown and ‘value’ is returned on the form.

As for OP: I’m not sure why your not getting numbers and not the words. I would ask why you need to call ajax to get the list? But just looking at the code you posted, I don’t think the ajax call is actually returning anything but I haven’t used ajax much.