Addev
Addev

Reputation: 32221

Insert rows in other tables on creation in yii

For the following database:

TABLES:
user: [id,username]
project: [id,name]
project_user_assignment: [user_id,project_id,role]

When a new project is being created I'd like to show a dropdown with the available users to manage the project and when saving it insert into project_user_assignment the row

[user_id,project_id,'manager']

I'm starter with yii and don't know where (class,method) I must do the insert and how to return an error if in the moment of the insert the query fails

Upvotes: 0

Views: 800

Answers (1)

Davide Vernizzi
Davide Vernizzi

Reputation: 1407

To display a drop down list in the you can use the foliowing code:

<?php echo CHtml::dropDownList(null, 
     'type',
     CHtml::listData(
        User::model()->findAll(),
        'id',
        'username',
     ),
     array('empty' => 'Select a manager from the list ... ', 'id'=>'manager_list')
  );?>

to update the corresponding field of the project_user_assignment model use the following:

 <?php
      <div class="row">
              <?php echo $form->labelEx($model,'user_id'); ?> // Here I assume you have the $model variable set to Project_user_assignemenet ... if not (which probably is the case since you are creating a new project, set a new $model2 variable in the controller and use $model2 instead of $model)
              <?php echo $form->textArea($model,'user_id'); ?>
              <?php echo $form->error($model,'user_id'); ?>
      </div>
 ?>
 <script>
     $('#manager_list').on('change', function(e) {
             $('#Project_user_assignemenet_user_id').val($(this).val());  // Here id maybe wrong! Check them.
             return true;
     });
</script>

and finally in the controller you just save the model.

Upvotes: 1

Related Questions