dongzhukuai8177
dongzhukuai8177
2015-12-29 10:19

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

已采纳

How change value 'userid' in field ActiveForm after click on button?

How it make?

I need to check field 'userid' and change value.

I not know how it make.


View:

_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>

Controller:

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,
            ]);
        }
    }

}

Model:

Account.php

class Account extends \yii\db\ActiveRecord
{

    public function rules()
    {

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

}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanqun9618 duanqun9618 6年前

    Try this in your controller:

    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,
            ]);
        }
    }
    
    点赞 评论 复制链接分享