2017-11-17 6 views
0

데이터를로드하기 위해 조건을 가져 와서 db에 저장하면 $ _POST는 값을 가져 오지만 이 방법은 다른 프로젝트에서 작동하지만 여기서는 작동하지 않습니다. if(isset($_POST['money']) && isset($_POST['username'])){을 사용하여 데이터를 저장하면 작동하지만 load() 기능은 작동하지 않습니다.

컨트롤러

public function actionSend() { 
    $model = new User(); 
    $model->getErrors(); 
    if ($model->load(Yii::$app->request->post())) { 
     $model->money = 'something'; 
     $model->username = 'something'; 
     $model->save(); 
    } 
    return $this->render('send', [ 
     'model' => $model 
    ]); 
} 

모델

<?php 

namespace app\models; 
use yii\db\ActiveRecord; 

use Yii; 

class User extends \yii\db\ActiveRecord { 
    public static function tableName() { 
     return 'user'; 
    } 

    public function rules() { 
     return [ 
      [['username', 'money'], 'safe'], 
      [['username', 'password'], 'string', 'max' => 15], 
      [['auth_key', 'access_token'], 'string', 'max' => 32], 
      [['money'], 'string', 'max' => 8], 
     ]; 
    } 

    public function attributeLabels() { 
     return [ 
      'id' => 'ID', 
      'username' => 'Username', 
      'password' => 'Password', 
      'auth_key' => 'Auth Key', 
      'access_token' => 'Access Token', 
      'money' => 'Money', 
     ]; 
    } 
} 

보기

<?php 
use yii\helpers\Html; 
use yii\bootstrap\ActiveForm; 
?> 

<h2>Send</h2> 

<?php $form = ActiveForm::begin([ 
    'layout' => 'horizontal', 
    'fieldConfig' => [ 
     'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>", 
     'labelOptions' => ['class' => 'col-lg-1 control-label'], 
    ], 
]); ?> 
    <?= $form->field($model, 'username')->textInput(['name' => 'username']) ?> 

    <?= $form->field($model, 'money')->textInput(['name' => 'money'])?> 

    <div class="form-group"> 
     <div class="col-lg-offset-1 col-lg-11"> 
      <?= Html::submitButton('Send', ['class' => 'btn btn-success']) ?> 
     </div> 
    </div> 

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

답변

3

변경이

public function actionSend() { 
    $model = new User(); 
    $model->getErrors(); 

    /* set the second parameters of load to empty string */ 
    if ($model->load(Yii::$app->request->post(), '')) { 
     $model->money = 'something'; 
     $model->username = 'something'; 
     $model->save(); 
    } 
    return $this->render('send', [ 
     'model' => $model 
    ]); 
} 
,369에 컨트롤러

load 방법의 구현을 검토 한 경우 load은 두 개의 매개 변수를 취합니다. 첫 번째는 할당 할 데이터이고 두 번째는 데이터의 접두사 이름입니다.

두 번째 매개 변수의 사용법을 보여주는 예를 살펴 보겠습니다.

$data1 = [ 
    'username' => 'sam', 
    'money' => 100 
]; 

$data2 = [ 
    'User' => [ 
     'username' => 'sam', 
     'money' => 100 
    ], 
], 

// if you want to load $data1, you have to do like this 
$model->load($data1, ''); 

// if you want to load $data2, you have to do like this 
$model->load($data2); 

// either one of the two ways, the result is the same. 
echo $model->username; // sam 
echo $model->money;  // 100 

그것이 도움이 될 수있는 희망 (우리는 당신의는 FormName이 User이라고 가정).