CActiveForm->dropDownList selected="selected"

Try to read about selection at php form.

same thing, still does not working

I have to experiment more :)

Maybe is problem in that my form model extends CFormModel instead CActiveRecord?

This is not very useful for me. I know how to do html markup, and how to receive and process data from forms, this question is about CActiveForm::dropDownList

Thx for reply.

could you please show your form code?

i m using CActiveForm.

really, in my form its selected automatically.

i have never do pseudo ‘if selected’ in option tags.

:mellow:

$form->dropDownList() automatically selects the attribute value from your model. So first check wether the ‘location’ attribute in your model has the correct value. If not, make sure you’ve declared it as a “safe attribute”. If the value is o.k. make sure, that your data list ($locations) really has a key with this value.

This is form model:




<?php


    /**

     * Form used for User profile edit

     */

    class ProfileForm extends CFormModel

    {


        public $username;

        public $email;

        public $location;

        public $infoText;


        public function rules() {

            return array();

        }


        public function attributeLabels() {

            return array(

                'username' => 'Korisničko ime',

                'email' => 'Email adresa',

                'location' => 'Lokacija',

                'infoText' => 'Kratki info',

            );

        }


    }



It’s very simple, and with just few fields.

This is controller that gathers data, and renders view:




<?php


    class ProfileController extends Controller

    {


        public function actionIndex() {

            $data['user'] = Users::model()->find("username='" . Yii::app()->user->id . "'");


            $data['model'] = new ProfileForm();


            //priprema podataka za listu lokacija

            $criteria = new CDbCriteria;

            $criteria->order = 'name ASC';

            $locations = Locations::model()->findAll($criteria);

            $data['locations'] = CHtml::listData($locations, 'id', 'name');


            $this->render('index', $data);

        }


        public function actionUpdate() {

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

                $user = Users::model()->find("username='".Yii::app()->user->id."'");

                $user->attributes = $_POST['ProfileForm'];


                if ($user->validate()) {

                    $user->save();

                    $this->redirect($this->createUrl('profile/index'));

                }

            }

        }


    }



This is Users model:




<?php


    /**

     * This is the model class for table "users".

     */

    class Users extends CActiveRecord

    {


        public $password2;

        public $rememberMe;

        public $verifyCode;

        private $_identity;

        /**

         * The followings are the available columns in table 'users':

         * @var integer $id

         * @var string $username

         * @var string $password

         * @var string $salt

         * @var string $email

         * @var integer $location

         * @var boolean $accEnabled

         */


        /**

         * Returns the static model of the specified AR class.

         * @return Users the static model class

         */

        public static function model($className=__CLASS__) {

            return parent::model($className);

        }


        /**

         * @return string the associated database table name

         */

        public function tableName() {

            return 'users';

        }


        /**

         * @return array validation rules for model attributes.

         */

        public function rules() {

            // NOTE: you should only define rules for those attributes that

            // will receive user inputs.

            return array(

                array('username, password, password2, email', 'required', 'on' => 'register'),

                array('password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'),

                array('username, email', 'unique', 'on' => 'register'),

                array('username, password, email', 'length', 'min' => 4, 'max' => 255, 'on' => 'register'),

                array('email', 'email', 'on' => 'register'),

                array('verifyCode', 'captcha', 'on' => 'register', 'allowEmpty' => !extension_loaded('gd')),

                array('username, password', 'required', 'on' => 'login'),

                array('accEnabled', 'accEnabled', 'on' => 'login'),

                array('rememberMe', 'boolean', 'on' => 'login'),

                // The following rule is used by search().

                // Please remove those attributes that should not be searched.

                array('id, username, email', 'safe', 'on' => 'AdminSearch'),

                array('username, location', 'safe', 'on' => 'UserSearch'),

                // password needs to be authenticated

                array('password', 'authenticate', 'on' => 'login'),

            );

        }


        /**

         * @return array relational rules.

         */

        public function relations() {

            // NOTE: you may need to adjust the relation name and the related

            // class name for the relations automatically generated below.

            return array(

			'location' => array(self::BELONGS_TO, 'Locations', 'id'), // this is experiment, maybe I can get that damn selected="selected" with this??? NO, I can't

            );

        }


    }



I’ve stripped out some functions from this post (eg. search functions, attributeLabels, login, accEnabled and so on, that I’ve think that is not important for this problem)

And, finally, The View, in all it’s glory :(




<?php

    $this->pageTitle = 'User profile';

?>


<!-- @todo Dovrsiti formu -->

<div class="form">

    <?php

        $form = $this->beginWidget('CActiveForm', array(

                    'id' => 'profile-form',

                    'action' => $this->createUrl('profile/update'),

                    'method' => 'post',

                    'enableAjaxValidation' => false,

                ));

    ?>


        <div class="row">

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

        <?php echo $form->textField($model, 'username', array('value' => $user->username, 'readonly' => 'readonly')); ?>

        </div>


        <div class="row">

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

        <?php echo $form->textField($model, 'email', array('value' => $user->email, 'readonly' => 'readonly')); ?>

        </div>


        <div class="row">

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

        <?php echo $form->dropDownList($model, 'location', $locations, array('prompt' => '(Odaberite lokaciju)')); ?>

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

        </div>


        <div class="row">

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

        <?php echo $form->textArea($model, 'infoText', $user->info); ?>

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

        </div>


        <div class="row">


        </div>


        <div class="row buttons">

        <?php echo CHtml::submitButton('Submit'); ?>

        </div>


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


</div><!-- form -->



Well, looking at this code-mess, I think that will be miracle to resolve my problem, but… I will. One day :)

I must confess that I don’t understand your answer :(

At all.

Please, let me describe to you what I have (tables etc…), and what I want to achieve. Maybe you will be able to help me better after that.

First, in db I have two tables ‘users’ and ‘locations’. I’ll try to create table structure here, omitting irrelevant fields.

users:




|   id   |   username   |   location   |

|    1   |   someUsr1   |   1          |

|    2   |   someUsr2   |   9          |



locations:




|   id   |   name                          |

|    1   | Bjelovarsko-bilogorska županija |

|    2   | someLoc2                        |

|   ...  | someLocN                        |



Table ‘locations’ is some kind of lookup table with prepopulated values

I’ve posted my models, controller and view above, now I will try to explain what happens when I’m using that.

I’m logged in, and I’m go to My Profile, I can see my form with prepopulated field (eg. username, email etc), I have dropdown list wit all correct values from ‘locations’ table:




<select name="ProfileForm[location]" id="ProfileForm_location">

<option value="">(Odaberite lokaciju)</option>

<option value="1">Bjelovarsko-bilogorska županija</option>

<option value="2">Brodsko-posavska županija</option>

<option value="3">Dubrovačko-neretvanska županija</option>

<option value="4">Istarska županija</option>

<option value="5">Karlovačka županija</option>

<option value="6">Koprivničko-križevačka županija</option>

<option value="7">Krapinsko-zagorska županija</option>

<option value="8">Ličko-senjska županija</option>

<option value="9">Međimurska županija</option>

<option value="10">Osječko-baranjska županija</option>

<option value="11">Požeško-slavonska županija</option>

<option value="12">Primorsko-goranska županija</option>

<option value="20">Šibensko-kninska županija</option>

<option value="13">Sisačko-moslavačka županija</option>

<option value="14">Splitsko-dalmatinska županija</option>

<option value="15">Varaždinska županija</option>

<option value="16">Virovitičko-podravska županija</option>

<option value="17">Vukovarsko-srijemska županija</option>

<option value="18">Zadarska županija</option>

<option value="19">Zagrebačka županija</option>

</select>



I can select one of these options and click Submit, after that in ‘users’ table location field will be updated to correct value (eg. 1 if I select <option value=“1”>Bjelovarsko-bilogorska županija</option>)

after that, if I refresh page I will see <option value="">(Odaberite lokaciju)</option> as selected option in drop down list, and list markup will be exactly the same as above, and I want it to be like this:




<select name="ProfileForm[location]" id="ProfileForm_location">

<option value="">(Odaberite lokaciju)</option>

<option value="1" selected="selected">Bjelovarsko-bilogorska županija</option>

<option value="2">Brodsko-posavska županija</option>

<option value="3">Dubrovačko-neretvanska županija</option>

<option value="4">Istarska županija</option>

<option value="5">Karlovačka županija</option>

<option value="6">Koprivničko-križevačka županija</option>

<option value="7">Krapinsko-zagorska županija</option>

<option value="8">Ličko-senjska županija</option>

<option value="9">Međimurska županija</option>

<option value="10">Osječko-baranjska županija</option>

<option value="11">Požeško-slavonska županija</option>

<option value="12">Primorsko-goranska županija</option>

<option value="20">Šibensko-kninska županija</option>

<option value="13">Sisačko-moslavačka županija</option>

<option value="14">Splitsko-dalmatinska županija</option>

<option value="15">Varaždinska županija</option>

<option value="16">Virovitičko-podravska županija</option>

<option value="17">Vukovarsko-srijemska županija</option>

<option value="18">Zadarska županija</option>

<option value="19">Zagrebačka županija</option>

</select> 



so it will show <option value="1" selected="selected">Bjelovarsko-bilogorska županija</option> as selected option

I hope that you can help me somehow.

Thanks in advance

EDIT: I just looked at table ‘locations’ with phpmyadmin, and I can confirm that key->value pairs are correct.

eg. 1->Bjelovarsko-bilogorska županija, 2->Brodsko-posavska županija etc…

Wow a lot of code :D

i do not know if i can help you, but i will try…




I'm logged in, and I'm go to My Profile,



is you redirect the page after login succesfuly or clik link something like this ?




<a href="http://example.com/profile/update/99" >My profile</a>



or maybe like this




<a href="http://example.com/index.php/profile/update?id=99" >My profile</a>



make sure you have $_GET[id] in profile update page. it will be invoke loadModel() action in controller

you can echo $_GET[‘id’];




	public function loadModel()

	{

		if($this->_model===null)

		{

			if(isset($_GET['id']))

				$this->_model=profile::model()->findbyPk($_GET['id']);

			if($this->_model===null)

				throw new CHttpException(404,'The requested page does not exist.');

		}

		return $this->_model;

	}



i dont see this method in you profilecontoller. ??

when you click submit,this method will be invoke.(Profileconttroller)




        public function actionUpdate() {

            $model=$this->loadModel();

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

                 /*  uncomment this to see array data form after submit

                 print_r($model->attributes=$_POST['ProfileForm']);

                 die();

                  */

		$model->attributes=$_POST['ProfileForm'];

			if($model->save())

                           $this->redirect($this->createUrl('profile/index'));

                }

            }

        }




if your form is in index page you can try this




       public function actionIndex() {

		

            $data['user'] = Users::model()->find("username='" . Yii::app()->user->id . "'");


            $data['model'] = new ProfileForm();


            //priprema podataka za listu lokacija

            $criteria = new CDbCriteria;

            $criteria->order = 'name ASC';

            $locations = Locations::model()->findAll($criteria);

            $data['locations'] = CHtml::listData($locations, 'id', 'name');


if(isset($_GET['id'])){

  $this->actionUpdate();

}else{

  $this->actionCreate();

}


            $this->render('index', $data);

        }



since its new model or loadmodel.

i hope this help you at least… :lol:

Hmm. Maybe then you should read the guide first? Most is described there. You might read it a second or third time, as it’s very compact.

The problem with your code is:

You’ve declared the attribute location to be safe in scenario UserMode (see your rules). But you don’t set this scenario in your actionUpdate, when you query for the user model. So: either make it safe in any scenario (remove ‘on’=>‘UserSearch’ from that rule) or set this scenario after you queried $user in your controller.

you can use CHtml::DropDownList and assigned a name with ‘location’

CHtml::dropDownList(‘location’, $model->locaton, $locatons)

Hope this can help you!! :rolleyes:

Well, for other people who may also been looking for this solution, there are several methods to solve this, the first two of which I don’t recommend:

  1. Assign the model’s attribute a default value. It has the problem of not being the best solution if the dropdownlist is multiselect. Besides, it is a model level solution for an interface issue: unless we are talking about a very sensitive decision, sometimes the default-selection is a matter of visualization only, sometimes it is a programmer’s whim to leave a default selection, but it doesn’t deeply affect the database, nor the model itself, nor the application gravely, so I think that the solution should be in the views layer.

  2. Creating a default value in the table. This is worse, I think: it uses a database-level solution for something that is a matter of visualization (read the argument of point 1).

  3. A more feasible and clearer solution is using the "options" entry in the array of htmloptions, I read it in the CHtml Dropdownlist documentation, but I applied it for an ActiveForm Dropdownlist. So in this example, if the reader wants the item with key value "3" tobe selected by default, she/he should use:

<?php echo $form->dropDownList($model,‘country_id’,$countries_array,array(‘empty’ => ‘’,

‘options’=>array(3=>array(‘selected’=>‘selected’))

));

Best Regards, and let me congratulate once more the founders of this absolutely great framework.

David López Salgado

Bogotá, Colombia, South America

Investigación y Programación

David! Muchas Gracias

That was exactly what I needed!

Tu esta EL hombre! (you are the man!)

<?php echo $form->dropDownList($model,‘country_id’,$countries_array,array(‘empty’ => ‘’,‘options’=>array(3=>array(‘selected’=>‘selected’))

));

thanks, it’s work

:lol: :lol: :lol: :lol:


<?php echo $form->dropDownList($model,'country_id',$countries_array,array('empty' => '',

'options'=>array(3=>array('selected'=>'selected'))

));



It helped me as well. Thank you very much! :)


<?php echo $form->dropDownList($model,'country_id',$countries_array,array('empty' => '',

'options'=>array(3=>array('selected'=>'selected'))

));

Helpful example for me too…

For ex…


echo CHtml::dropDownList('designation_id', 'designation_id',  CHtml::listData(VenueDesignation::model()->findAll("status='1'"),'id','designation_name'),  array('options' => array($resultSet->designation_id =>  array('selected' => true),'class'=>'col_165')));

The solution for my issue was to make sure I had declared a validation rule in the model. Once that was done, Yii worked it’s magic, and the correct value is auto-selected.

Thank you. It works for me…

Hi,

For multiselect drop down use below code:





$selectedCategory = explode(",", $model->category_ids);

			$selCategory = array();

			foreach($selectedCategory as $category) {

				$selCategory[$category] = array('selected'=>'selected');

			}

			

			

			echo CHtml::activeDropDownList($model, 'category_ids[]',

			CHtml::listData($categoryList,'id', 'name'),

			array(

				

				'options' => $selCategory,

				'empty'=>'Select Category',

				'multiple' => 'multiple',

				'size' => 10

			));




Thanks, you saved me