2016-09-10 3 views
1

작업 테이블에서 새 행 (사용자 위치)을 성공적으로 삽입하고 작업 업데이트시 성공적으로 업데이트하지만 문제는 ation에서 업데이트됩니다. location_id 필드는 항상 비어 있습니다. 그것은 userlocations 테이블에서 location_id를 가져 와서 업데이트시 필드를 채워야하지만 그렇지 않습니다.Yii2 Select2 - 업데이트 - 접합 테이블에서 선택된 값

데이터베이스 : http://i.stack.imgur.com/JFjdz.png

UserController :

<?php 

namespace backend\controllers; 

use Yii; 
use backend\models\User; 
use backend\models\UserSearch; 
use yii\web\Controller; 
use yii\web\NotFoundHttpException; 
use yii\filters\VerbFilter; 
use yii\helpers\ArrayHelper; 

use backend\models\Locations; 
use backend\models\Userlocations; 

class UserController extends Controller 
{ 

public function behaviors() 
{ 
    return [ 
     'verbs' => [ 
      'class' => VerbFilter::className(), 
      'actions' => [ 
       'delete' => ['POST'], 
      ], 
     ], 
    ]; 
} 

/** 
* Lists all User models. 
* @return mixed 
*/ 
public function actionIndex() 
{ 
    $searchModel = new UserSearch(); 
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams); 

    return $this->render('index', [ 
     'searchModel' => $searchModel, 
     'dataProvider' => $dataProvider, 
    ]); 
} 

/** 
* Displays a single User model. 
* @param integer $id 
* @return mixed 
*/ 
public function actionView($id) 
{ 
    return $this->render('view', [ 
     'model' => $this->findModel($id), 
    ]); 
} 

/** 
* Creates a new User model. 
* If creation is successful, the browser will be redirected to the 'view' page. 
* @return mixed 
*/ 
public function actionCreate() 
{ 
    $model = new User(); 
    $locations = ArrayHelper::map(Locations::find()->all(), 'id', 'name'); 
    $userlocations = new Userlocations(); 

    if ($model->load(Yii::$app->request->post())) { 

     $model->setPassword($model->password); 
     $model->generateAuthKey(); 

     $userlocations->load(Yii::$app->request->post()); 

     if ($model->save() && !empty($userlocations->location_id)){ 

      foreach ($userlocations->location_id as $location_id) { 
       $userlocations = new Userlocations(); 
       $userlocations->setAttributes([ 
        'location_id' => $location_id, 
        'user_id' => $model->id, 
       ]); 
       $userlocations->save(); 
      } 
     } 

     return $this->redirect(['user/index']); 
    } else { 
     return $this->render('create', [ 
      'model' => $model, 
      'locations' => $locations, 
      'userlocations' => $userlocations, 
     ]); 
    } 
} 

/** 
* Updates an existing User model. 
* If update is successful, the browser will be redirected to the 'view' page. 
* @param integer $id 
* @return mixed 
*/ 
public function actionUpdate($id) 
{ 
    $model = $this->findModel($id); 
    $locations = ArrayHelper::map(Locations::find()->all(), 'id', 'name'); 
    $userlocations = new Userlocations(); 

    if ($model->load(Yii::$app->request->post()) && $model->save()) { 

     Userlocations::deleteAll(['user_id' => $id]); 

     $userlocations->load(Yii::$app->request->post()); 

     if (!empty($userlocations->location_id)){ 
      foreach ($userlocations->location_id as $location_id) { 
       $userlocations = new Userlocations(); 
       $userlocations->setAttributes([ 
        'location_id' => $location_id, 
        'user_id' => $model->id, 
       ]); 
       $userlocations->save(); 
      } 
     } 

     return $this->redirect(['user/index']); 
    } else { 

     return $this->render('update', [ 
      'model' => $model, 
      'locations' => $locations, 
      'userlocations' => $userlocations, 
     ]); 
    } 
} 

/** 
* Deletes an existing User model. 
* If deletion is successful, the browser will be redirected to the 'index' page. 
* @param integer $id 
* @return mixed 
*/ 
public function actionDelete($id) 
{ 
    $this->findModel($id)->delete(); 

    return $this->redirect(['index']); 
} 

/** 
* Finds the User model based on its primary key value. 
* If the model is not found, a 404 HTTP exception will be thrown. 
* @param integer $id 
* @return User the loaded model 
* @throws NotFoundHttpException if the model cannot be found 
*/ 
protected function findModel($id) 
{ 
    if (($model = User::findOne($id)) !== null) { 
     return $model; 
    } else { 
     throw new NotFoundHttpException('The requested page does not exist.'); 
    } 
} 

}

사용자 모델 :

class User extends \common\models\User 
{ 

public $password; 

/** 
* @inheritdoc 
*/ 
public static function tableName() 
{ 
    return 'User'; 
} 

/** 
* @inheritdoc 
*/ 
public function rules() 
{ 
    return [ 
     [['username', 'password'], 'required'], 
     [['status', 'created_at', 'updated_at'], 'integer'], 
     [['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255], 
     [['auth_key'], 'string', 'max' => 32], 
     [['username'], 'unique', 'message' => 'Username already taken!'], 
     [['email'], 'unique'], 
     [['password_reset_token'], 'unique'], 
    ]; 
} 

/** 
* @inheritdoc 
*/ 
public function attributeLabels() 
{ 
    return [ 
     'id' => 'ID', 
     'username' => 'Username', 
     'auth_key' => 'Auth Key', 
     'password_hash' => 'Password Hash', 
     'password_reset_token' => 'Password Reset Token', 
     'email' => 'Email', 
     'status' => 'Status', 
     'created_at' => 'Created At', 
     'updated_at' => 'Updated At', 
    ]; 
} 

}

내 FO RM : 여러 위치는

<?php 

use yii\helpers\Html; 
use yii\widgets\ActiveForm; 
use yii\helpers\ArrayHelper; 
use kartik\select2\Select2; 

use backend\models\Locations; 

?> 

<div class="user-form"> 

<?php $form = ActiveForm::begin(); ?> 

<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?> 

<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?> 

<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?> 

<?= $form->field($userlocations, 'location_id')->widget(Select2::classname(), [ 
    'data' => ArrayHelper::map(Locations::find()->all(), 'id', 'name'), 
    'size' => Select2::MEDIUM, 
    'options' => ['placeholder' => 'Select a location ...', 'multiple' => true], 
    'pluginOptions' => [ 
     'allowClear' => true, 
    ], 
]); ?> 

<?= $form->field($model, 'status')->dropDownList(['10' => 'Active', '0' => 'Inactive']) ?> 

<div class="form-group"> 
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> 
</div> 

<?php ActiveForm::end(); ?> 

+0

@PurpleHaze 사용자 모델을 표시 할 수 있습니까? 사용자 테이블에 location_id 필드가 없습니다. –

+0

서버로 전송되는 게시물 데이터의 스냅 샷을 표시합니다. 크롬 개발자 도구의 네트워크 탭을 사용하여 데이터 게시 –

+0

하나 이상의 테이블에서 변경 작업을 수행하는 경우 항상 트랜잭션에서 사용하십시오. –

답변

0

가 선택 아래로 플러그인 코드를 사용합니다.

<?= Select2::widget([ 
     'name' => 'Userlocations[location_id]', 
     'value' => $location_ids, // initial value 
     'data' => ArrayHelper::map(Locations::find()->all(), 'id', 'name'), 
     'options' => ['placeholder' => 'Select your locations...', 'multiple' => true], 
     'pluginOptions' => [ 
      'tags' => true, 
      'maximumInputLength' => 10 
     ], 
    ]); ?> 

$ location_ids 이전에 하나 개 이상의 테이블에 대한 변경을 할 때 당신이 트랜잭션에 그것을 확인, 기억 time.Also 작성시 선택한 위치에 배열 될 것입니다.

+0

감사합니다. Kiran : D – PupleHaze