单击按钮后如何更改字段ActiveForm中的值?

时间:2015-12-29 10:19:27

标签: php yii2

点击按钮后,如何在ActiveForm字段中更改值'userid'

它如何制作?

我需要检查字段'userid'并更改值。

我不知道它是怎么做的。

查看:

_form.php这个

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

?>

<div class="account-form">

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

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

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

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

Create.php

<div class="account-create">

    <h1><?= Html::encode($this->title) ?></h1>

    <?= $this->render('_form', ['model' => $model,]) ?>

</div>

控制器:

AccountController.php

class AccountController extends Controller
{

public function actionCreate()
    {
        $model = new Account();

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

         return $this->redirect(['view', 'id' => $model->userid]);
        } else {

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

}

型号:

Account.php

class Account extends \yii\db\ActiveRecord
{

    public function rules()
    {

        return [
            [['userid'], 'required']
        ];
    }

}

1 个答案:

答案 0 :(得分:1)

在你的控制器中试试这个:

public function actionCreate()
{
    $model = new Account();

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

        $model->attributes = $_POST['Account'];
        $model->userid = 123;

        /* in case you had errors
        // $model->validate();
        // var_dump($model->getErrors());
        */

        if($model->save()){

            return $this->redirect(['view', 'id' => $model->userid]);
        }
    }
    else{

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