简体   繁体   中英

How to retrieve the value from Drop down list into the Controller in Yii?

I have a div inside a form but I'm not quite sure how to retrieve the chosen value into the controller:

<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'system-users-form',
'enableAjaxValidation'=>false,
)); ?>

<p class="note">Fields with <span class="required">*</span> are required.</p>

<?php echo $form->errorSummary($model); ?>

<button id="abutton">Already a Supplier</button>
<br>
&nbsp;
&nbsp;

<div class="row" id="toshow" style="display:none" name="suppliers"> 
<?php $supplier = SupplierHead::model()->findAll();
   $list = CHtml::listData($supplier ,'head_id','head_name'); 
   echo $form->DropDownList($model,'party_id', 
   $list, array('prompt'=>'Select Supplier')); 
?> 
</div>



<script>
$(document).ready(function() {
   $("#abutton").click(function(e){
      e.preventDefault();
      $("#toshow").css('display', 'block');
   });
});
</script>

<div class="row">
    <?php echo $form->labelEx($model,'username'); ?>
    <?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>200)); ?>
    <?php echo $form->error($model,'username'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'password'); ?>
    <?php echo $form->passwordField($model,'password',array('size'=>60,'maxlength'=>255)); ?>
    <?php echo $form->error($model,'password'); ?>
</div>

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

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

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

Note that this row also belongs to another model. How would I retrieve this inside another controller?

Controller Code:

 public function actionCreate()
    {
        $model = new SystemUsers;
        $modelParties = new Parties;
        $modelPersons = new Persons;
        $supplierHead = new SupplierHead;
    //  $modelPR = new PartyRoles;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($invoice);

if (isset($_POST['SystemUsers']))
    {
        $model->attributes = $_POST['SystemUsers'];
        Yii::app()->db->createCommand("insert into parties (party_type_id) values ('1')")->execute();           
        $id = Yii::app()->db->lastInsertId;

        $_POST["SupplierHead"]["party_id"];
        $model->password = md5($model->password);
        $model->party_id = $id;
        $model->status = "Approved";
        $model->date_modified = new CDbExpression('NOW()');
        $email = $model->username;
        if($company != null)
            {

                Yii::app()->db->createCommand("insert into persons (party_id,email,company_name) values ('".$id."','".$email."','".$company."')")->execute();
            }
        Yii::app()->db->createCommand("insert into persons (party_id,email) values ('".$id."','".$email."')")->execute();
        Yii::app()->db->createCommand("insert into party_roles(party_id,role_id) values ('".$id."','2')")->execute();
  /*
        $valid = true; 
        $valid &= $model->validate(); 
        $valid &= $modelParties->validate(); 
              if($valid)
                {   
        $modelParties->save();
        $model->party_id = $modelParties->getPrimaryKey();  */

        if($model->save())
            echo ("<SCRIPT LANGUAGE='JavaScript'>
                    window.alert('User Created')
                    window.location.href='create';  
                </SCRIPT>");

//      }
        else $this->redirect(array('views22','id'=>$model->id));
 }

$this->render('create',array(
  'parties'=>$modelParties,
  'model'=>$model,
));

}

Model for SystemUsers:

public function tableName()
{
    return 'system_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', 'required'),
        array('isLogin', 'numerical', 'integerOnly'=>true),
        array('date_modified','default',
          'value'=>new CDbExpression('NOW()'),
          ),
        array('date_last_login','default',
          'value'=>new CDbExpression('NOW()'),
          ),
        array('date_created','default',
          'value'=>new CDbExpression('NOW()'),
          ),
        array('status','default','value'=>'Approved'),
        array('user_role','default','value'=>'MEMBER'),
        array('isLogin','default','value'=>'1'),

        array('username', 'length', 'max'=>200),
        array('password', 'length', 'max'=>255),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
    );
}

EDIT

I added my model and the rest of the form to show you the confusion. The dropdown list div is value i'm trying to input into a different model and it does not exist as an attribute for system_users so It's not going through the POST.

First make sure that your model's attribute has a safe rule. Second, in controller get a dump to see what have been sent via POST request. Do like below:

CVarDumper::dump($_POST,5678,true);
Yii::app()->end();

Third, find your dropdown element in the dump you have. In Yii, You can also get a post value like below:

Yii::app()->request->getPost('YOUR DROPDOWN NAME');

UPDATE

As I said first, You must make sure that your attribute is safe. In your model add a rule like below:

array('THE NAME OF YOUR DROPDOWN','safe'),

I hope it helps.

@charlesisjan this depends on debugging also. Actually $_POST is an array with a collection of arrays, and further these arrays are a collection of key value pairs like

array(
    'key'=>'value'
)

First you need to ensure whether party_id is being submitted in the form. I am sure it is being submitted.
Now after

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

use

CVarDumper::Dump($_POST,100,true);
die();

I am using a dummy code. it will show you the $_POST array like

array ( 'User' => array ( 'username' => 'rafasd' 'password' => 'asdfas' 'email' => 'asd@yahoo.com' ) 'yt0' => '' )

in above code as user is itself an array so u can access the username as

$_POST['User']['username']

Now try to find out where does party_id is located in the $_POST array. When u find that u can access its value using above mentioned pattern

you can get as :

 $id =  $_POST["SystemUsers"]["party_id"]

As per your code, drop-down name will be set as "Model_name[Field_name]".

In your action, you can see the line

$some_variable  = $_POST["SystemUsers"]; // SystemUsers is model name

Please change your

 $_POST["SupplierHead"]["party_id"];

with this

 $_POST["SystemUsers"]["party_id"];

in your controller action create,I think error is here! Also if party_id is Your primary key then don't use in drop down, create new public variable in your model and use here in drop down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM