Nadeem Iqbal Nadeem Iqbal - 5 days ago 5
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


<?php
/* SubtopicsController */
/* @var $model Subtopics */
/* @var $form CActiveForm */
?>

<div class="form">
<?php
$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>

<div class="row">
// This is the subjected dropdown
<?php echo $form->labelEx($model, 'topic_id'); ?>
<?php
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>


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

<?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

Answer

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".

Topic::model()->findAll()

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

Cheers

Comments