Nadeem Iqbal Nadeem Iqbal - 1 month ago 13
PHP Question

Set Default Value in DropDownList Yii PHP

I have an admin panel in yii where I can edit/update subtopics And topics.

And On that edit/update page of subtopics there is a foreign key value referencing to the topics table.

I have a dropdown, which I have filled with the names of Topics on behalf of topic ids, but the problem is that the dropdown should show me the correct selected value of topic in dropdown. Instead it is showing the first value.

My Code

/* SubtopicsController */
/* @var $model Subtopics */
/* @var $form CActiveForm */

<div class="form">
$form = $this->beginWidget('CActiveForm', array(
'id' => 'subtopics-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
//Some Irrelevant Code

<div class="row">
<?php echo $form->labelEx($model, 'name'); ?>
<?php echo $form->textArea($model, 'name', array('rows' => 1, 'cols' => 50)); ?>
<?php echo $form->error($model, 'name'); ?>

<div class="row">
// This is the subjected dropdown
<?php echo $form->labelEx($model, 'topic_id'); ?>
echo $form->dropDownList($model, 'topic_id', Subtopics::model()->get_AllTopics(), array(
'ajax' => array(
'data' => array('topic_id' => 'js:this.value'),
<?php echo $form->error($model, 'topic_id'); ?>

<div class="row buttons">
<?php ?>
echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save');

<?php $this->endWidget(); ?>

What it is showing

<code>What it is showing</code>

And this is the option I want to be selected

And this is the option I want to be selected


You don't need that ajax option for this job, You just need to load all topics at the start

<?php echo $form->dropDownList($model,'topic_id', CHtml::listData(Topic::model()->findAll(), 'id', 'name')); ?>

Last two parameters of CHTML::listData are column names in topic table, primary key and what you want to display. I assumed those are "id" and "name".


Of course this can be customized to suit your needs. I even like to put in a method

This will always bound value in drop down on update