active record massive assignment

Hi,

Does someone know where in the Yii framework is done the massive assignment?

I mean the


$model = new MyModel(); $model->attributes = $_POST(['MyModel']);

Because for me it doesn’t work whereas I did what it is recommended in the tutorial …

Thanks

It’s set in the setAttributes method - http://www.yiiframework.com/doc/api/1.1/CModel#setAttributes-detail

Can you explain more on “it doesn’t work whereas I did what it is recommended in the tutorial”… what have you done exactly?.. and what is not working?

I create a searchFormModel, formView, an action in a controller.

In Firebug I see that correct data are posted MyModel[xxx]

My action’s code is somewhat classic. I just try to assign all the Posted data to the model.

in my view


<div id="mySearch-container">

    <div class="form">

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

         'id'=>'mySearch',

         'enableAjaxValidation'=>false,

    )); ?>


        <fieldset id="field-one">

         <div class="row col1">

              <?php echo $form->dropDownList(

                $model,

                'marque_id',

                CHtml::listData(Marque::model()->findAll(),'id','nom'),

                array(

                   'ajax'=>array(

                        'type'=>'post',

                        'url'=>CController::createUrl('voiture/dynamicModeles'),

                        'success'=>'

                            function(data) {

                                $("#MySearchForm_modele_id").empty().append(data);

                                $("#MySearchForm_version_id").empty().append("<option>Choisissez une version</option>");

                            }

                        '


                    ),

                    'prompt' => 'Choisissez une marque'

                )


               ); ?>

         </div>

         <div class="row col2">

              <?php echo $form->dropDownList(

                    $model,

                    'modele_id',

                    array(),

                    array(

                       'ajax'=>array(

                            'type'=>'post',

                            'url'=>CController::createUrl('voiture/dynamicVersions'),

                            'update'=>'#MySearchForm_version_id',


                        ),

                        'prompt'=>'Choisissez un modèle'

                    )

                   );

              ?>

         </div>

         <div class="row col3">

              <?php echo $form->dropDownList(

                $model,

                'version_id',

                array(),

                array(

                    'prompt'=>'Choisissez une version'

                )


               );

              ?>

         </div>

        </fieldset>

        <fieldset id="field-two">

             <div class="row col1">

                  <?php echo $form->dropdownList($model,'boiteVitesse_id',Voiture::getBoiteVitesse(),array('prompt' =>'Boîte Vitesse')); ?>

             </div>


             <div class="row col2">

                  <?php  echo $form->dropdownList($model,'motorisation_id',CHtml::listdata(Motorisation::model()->findAll(),'id','nom'),

                          array('prompt' =>'Motorisation') ); ?>


             </div>

            <div class="row col3">

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

              <?php echo $form->textField($model,'anneeMin'); ?>

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

            </div>

            <div class="row col4">

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

              <?php echo $form->textField($model,'anneeMax'); ?>

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

            </div>

        </fieldset>


        <fieldset id="field-three">

            <div class="row col1">

                <p class="prix-container">Prix Min:<span id="prix-min-label">3000 €</span></p>

                <?php

                    $this->widget('zii.widgets.jui.CJuiSliderInput', array(

                        'model'=>$model,

                        'name'=>'prix-min',

                        'attribute'=>'prixMin',

                        'event'=>'stop',


                        // additional javascript options for the slider plugin

                        'options'=>array(

                            'min'=>3000,

                            'max'=>105000,

                            'step'=>5000,

                            'value'=>3000,

                            'range'=>"min",

                            'slide'=>'js:function( event, ui ) {

                                        $( ".prix-container span#prix-min-label" ).empty().text(  ui.value+"€" );

                                   }'

                        ),

                        'htmlOptions'=>array(

                            'style'=>'height:20px;min-width:150px;'

                        ),

                    ));

                ?>

            </div>

            <div class="row col2">

                <p class="prix-container">Prix Max:<span id="prix-max-label">105000 €</span></p>

                <?php

                    $this->widget('zii.widgets.jui.CJuiSliderInput', array(

                        'model'=>$model,

                        'name'=>'prix-max',

                        'attribute'=>'prixMax',

                        'event'=>'stop',

                        // additional javascript options for the slider plugin

                        'options'=>array(

                            'min'=>3000,

                            'max'=>105000,

                            'step'=>5000,

                            'value'=>105000,

                            'range'=>"max",

                            'slide'=>'js:function( event, ui ) {

                                        $( ".prix-container span#prix-max-label" ).empty().text(  ui.value+"€" );

                                   }'

                        ),

                        'htmlOptions'=>array(

                            'style'=>'height:20px;'

                        ),

                    ));

                ?>

            </div>

        </fieldset>

        <hr class="separation"/>

         <div class="row buttons">

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

         </div>


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

    </div>

</div>

My Model :


<?php




class MySearchForm extends CFormModel

{

	public $marque_id;

	public $modele_id;

	public $version_id;

     public $motorisation_id;

     public $boiteVitesse_id;

     public $anneeMin;

     public $anneeMax;

     public $prixMin;

     public $prixMax;




	/**

	 * Declares the validation rules.

	 * The rules state that username and password are required,

	 * and password needs to be authenticated.

	 */

	public function rules()

	{

		return array(

			array('anneeMin,anneeMax', 'safe'),




		);

	}


	/**

	 * Declares attribute labels.

	 */

	public function attributeLabels()

	{

		return array(

		);

	}





}



And in my controller, something which will revolutionize the software industry :D


	public function actionIndex()

	{


         $mySearch = new MySearchForm();

         // On traite la recherche si on récupère les éléments du Search

         if (isset($_POST["MySearchForm"])) {

            $mySearch->attributes = $_POST['MySearchForm'];

            // Assigment Doesn't work ....

            print_r($mySearch);

         }

         

		$dataProvider=new CActiveDataProvider(

                  'Voiture',

                  array(


                      'criteria'=>array(

                          'condition'=>'is_occasion=1',

                      ),

                      'pagination'=>array(

                            'pageSize'=>10,

                      ),

                  ));


          $this->render('index',array(

			'dataProvider'=>$dataProvider,

               'model' => $mySearch

		));

	}

Then no assigment. This is my problem …

At the place where you check with print_r($mySearch)… try to see what is POSTed… like print_r($_POST[‘MySearchForm’] )

I obtain the right posted value.

But I feel my problem comes from the concept of safe data …

Hmmm I was right. By declaring all data safe in the rule array of the Model I obtain the assigment.

But is there a way to bypass this ?

I mean in the setAttributes there is an option parameter to say whether I have to assign only safe data or unsafe …

Is there a way to say "not safe" ? because I do not master the mechanism beyond the


$mySearch->attributes = $_POST['MySearchForm'];

I mean the ‘=’ operator

which seems to call the setAttributes

Check the documentation for massive assignment - http://www.yiiframework.com/doc/guide/1.1/en/form.model#securing-attribute-assignments

CModel->attributes property has a getter/setter - http://www.yiiframework.com/doc/api/1.1/CModel#attributes-detail

so when you assign a value to it it calls the setAttributes() method…