本文介绍了Yii2 一个动作中的多种形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单个操作中处理多个表单的正确方法是什么?

这是我的模型/MembersBans.php

<?php命名空间应用程序模型;使用 Yii;使用 yiiehaviorsTimestampBehavior;使用 appmodelsMembers;class MembersBans 扩展 yiidbActiveRecord {公共 $ 用户名;公共静态函数表名(){返回'{{%members_bans}}';}公共静态函数primaryKey() {返回数组('ban_id');}公共功能行为(){返回 [['类' =>TimestampBehavior::className(),'createdAtAttribute' =>'添加日期','updatedAtAttribute' =>'最近更新时间',],];}公共函数规则(){返回 [[['ban_id', 'ban_memberid', 'date_ added', 'last_updated'], 'integer'],[['用户名', 'end_date'], '安全'],['end_date', 'date', 'format' =>'yyyy-mm-dd'],[['ban_ip'], 'string', 'max' =>40],[['原因'],'字符串','最大'=>[255]];}公共函数属性标签(){返回 ['ban_id' =>Yii::t('app', 'ID на бана'),'ban_memberid' =>Yii::t('app', 'Потребителско ID'),'用户名' =>'Потребителско име','ban_ip' =>Yii::t('app', 'IP адрес'),'结束日期' =>Yii::t('app', 'Дата на изтичане'),'原因' =>Yii::t('app', 'Причина за бана'),添加日期"=>Yii::t('app', 'Дата на добавяне'),];}公共函数 getMemberBans() {$bans = $this->find()->where('ban_memberid');返回 $bans;}公共函数 getIpBans() {$bans = $this->find()->where('ban_ip');返回 $bans;}公共函数 getMember() {return $this->hasOne(Members::className(), ['member_id' => 'ban_memberid']);}公共函数banMember() {$memberInfo = Members::findByUsername($this->username);如果($memberInfo){$this->ban_memberid = $memberInfo->member_id;如果 ($this->save()) {Yii::$app->session->setFlash('alert-success', 'Потребителят беше успешно блокиран.');} 别的 {Yii::$app->session->setFlash('alert-error', 'Възникна грешка при блокирането на потребителя.');}} 别的 {Yii::$app->session->setFlash('alert-error', 'Не съществува потребител с това потребителско име.');}}公共函数banIp() {如果 ($this->save()) {Yii::$app->session->setFlash('alert-success', 'IP адресът беше успешно блокиран.');} 别的 {Yii::$app->session->setFlash('alert-error', 'Възникна грешка при блокирането на IP адреса.');}}

}

我的控制器/MembersBansController.php:

public function actionList() {$membersBans = new MembersBans();if ($membersBans->load(Yii::$app->request->post('banMember'))) {$membersBans->banMember();}if ($membersBans->load(Yii::$app->request->post('banIp'))) {$membersBans->banIp();}返回 $this->render('list', ['membersBans' =>$membersBans,]);}

观看次数/会员-禁止/列表:

<?php$activeForm = ActiveForm::begin(['id' =>'禁止会员','启用客户端验证' =>真的,'enableAjaxValidation' =>真的,'validateOnSubmit' =>真的,'validateOnChange' =>真的,'validateOnType' =>真的,])?><?= $activeForm->field($membersBans, 'username', ['模板' =>'{标签}{输入}{提示}{错误}'])-> textInput(['class' => 'form-control', 'placeholder' => 'Въведете потребителско име']);?><?= $activeForm->field($membersBans, 'end_date', ['模板' =>'{标签}{输入}{提示}{错误}'])-> textInput(['class' => 'form-control datepicker', 'placeholder' => 'Въведете период на бана']);?><?= $activeForm->field($membersBans, 'reason', ['模板' =>'{标签}{输入}{提示}{错误}'])-> textInput(['class' => 'form-control', 'placeholder' => 'Въведете причина за бана']);?><div class="form-group"><?= Html::submitButton('Добави', ['type' => 'submit', 'class' => 'btn btn-default']) ?>

<?php ActiveForm::end()?>

<div class="the-box"><?php$activeForm = ActiveForm::begin(['id' =>'banIp','启用客户端验证' =>真的,'enableAjaxValidation' =>真的,'validateOnSubmit' =>真的,'validateOnChange' =>真的,'validateOnType' =>真的,])?><?= $activeForm->field($membersBans, 'ban_ip', ['模板' =>'{标签}{输入}{提示}{错误}'])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете IP адрес или цяла мрежа']);?><?= $activeForm->field($membersBans, 'end_date', ['模板' =>'{标签}{输入}{提示}{错误}'])-> textInput(['class' => 'form-control datepicker', 'placeholder' => 'Въведете период на бана']);?><?= $activeForm->field($membersBans, 'reason', ['模板' =>'{标签}{输入}{提示}{错误}'])-> textInput(['class' => 'form-control', 'placeholder' => 'Въведете причина за бана']);?><div class="form-group"><?= Html::submitButton('Добави', ['type' => 'submit', 'class' => 'btn btn-default']) ?>

<?php ActiveForm::end() ?>

而且它似乎不起作用.有什么想法吗?

解决方案

ActiveForm 中的 ID 并不意味着 $_POST 中的 id.你应该使用:

$membersBans->load(Yii::$app->request->post())

$membersBans->load(Yii::$app->request->post('MembersBans'))

用于从表单加载属性.

例如来自 CeBe 的多个表单 (http://www.yiiframework.com/forum/index.php/topic/53935-solved-subforms/page__p__248184#entry248184)

公共函数actionCreate(){$user = 新用户;$profile = 新配置文件;if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && 模型::validateMultiple([$user, $profile])) {$user->save(false);//跳过验证,因为模型已经验证$profile->user_id = $user->id;//不需要在 user_id 上设置验证规则,因为你自己设置了$profile-save(false);return $this->redirect(['view', 'id' => $user->id]);} 别的 {返回 $this->render('create', ['用户' =>$用户,'个人资料' =>$个人资料,]);}}

在您的 action 中,您使用一个 model.我认为您应该将 MembersBans 扩展到 MembersBansIp 类.还有你的action:

公共函数 actionList() {$membersBans = new MembersBans();$membersBansIp = new MembersBansIp();if ($membersBans->load(Yii::$app->request->post())) {$membersBans->banMember();}if ($membersBansIp->load(Yii::$app->request->post())) {$membersBansIp->banIp();}返回 $this->render('list', ['membersBans' =>$membersBans,'membersBansIp' =>$membersBansIp,]);}

view中:

'禁止会员',])?><?= $activeForm->field($membersBans, 'fieldMembersBans') ?><?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?><?php ActiveForm::end() ?><?php$activeForm = ActiveForm::begin(['id' =>'banMemberIp',])?><?= $activeForm->field($membersBansIp, 'usernameMembersBansIp') ?><?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?><?php ActiveForm::end() ?>

编辑

我放了你的代码.他是工作.https://yadi.sk/i/y7PkwGUPekjPD https://yadi.sk/i/h8dCYQz3ekk2B

但是我把控制器改成了这个

$membersBans = new MembersBans();if ($membersBans->load(Yii::$app->request->post())) {$membersBans->banMember();}if ($membersBans->load(Yii::$app->request->post())) {$membersBans->banIp();}

model中将Members改为User,因为我没有Members对象:

$memberInfo = User::findByUsername($this->username);如果($memberInfo){$this->ban_memberid = $memberInfo->id;

简历:您的代码有效.更改controller,我是怎么写的.

Which is the right way to handle multiple forms in a single action?

Here is my models/MembersBans.php

<?php

namespace appmodels;

use Yii;
use yiiehaviorsTimestampBehavior;
use appmodelsMembers;

class MembersBans extends yiidbActiveRecord {

public $username;

public static function tableName() {
    return '{{%members_bans}}';
}

public static function primaryKey() {
    return array('ban_id');
}

public function behaviors() {
    return [
        [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'date_added',
            'updatedAtAttribute' => 'last_updated',
        ],
    ];
}

public function rules() {
    return [
        [['ban_id', 'ban_memberid', 'date_added', 'last_updated'], 'integer'],
        [['username', 'end_date'], 'safe'],
        ['end_date', 'date', 'format' => 'yyyy-mm-dd'],
        [['ban_ip'], 'string', 'max' => 40],
        [['reason'], 'string', 'max' => 255]
    ];
}

public function attributeLabels() {
    return [
        'ban_id' => Yii::t('app', 'ID на бана'),
        'ban_memberid' => Yii::t('app', 'Потребителско ID'),
        'username' => 'Потребителско име',
        'ban_ip' => Yii::t('app', 'IP адрес'),
        'end_date' => Yii::t('app', 'Дата на изтичане'),
        'reason' => Yii::t('app', 'Причина за бана'),
        'date_added' => Yii::t('app', 'Дата на добавяне'),
    ];
}

public function getMemberBans() {
    $bans = $this->find()->where('ban_memberid');
    return $bans;
}

public function getIpBans() {
    $bans = $this->find()->where('ban_ip');
    return $bans;
}

public function getMember() {
    return $this->hasOne(Members::className(), ['member_id' => 'ban_memberid']);
}

public function banMember() {
    $memberInfo = Members::findByUsername($this->username);
    if ($memberInfo) {
        $this->ban_memberid = $memberInfo->member_id;
        if ($this->save()) {
            Yii::$app->session->setFlash('alert-success', 'Потребителят беше успешно блокиран.');
        } else {
            Yii::$app->session->setFlash('alert-error', 'Възникна грешка при блокирането на потребителя.');
        }
    } else {
        Yii::$app->session->setFlash('alert-error', 'Не съществува потребител с това потребителско име.');
    }
}

public function banIp() {
    if ($this->save()) {
        Yii::$app->session->setFlash('alert-success', 'IP адресът беше успешно блокиран.');
    } else {
        Yii::$app->session->setFlash('alert-error', 'Възникна грешка при блокирането на IP адреса.');
    }
}

}

My controllers/MembersBansController.php:

public function actionList() {
    $membersBans = new MembersBans();
    if ($membersBans->load(Yii::$app->request->post('banMember'))) {
        $membersBans->banMember();
    }
    if ($membersBans->load(Yii::$app->request->post('banIp'))) {
        $membersBans->banIp();
    }
    return $this->render('list', [
                'membersBans' => $membersBans,
    ]);
}

views/members-bans/list:

<div class="the-box">
    <?php
    $activeForm = ActiveForm::begin([
        'id'                     => 'banMember',
        'enableClientValidation' => true,
        'enableAjaxValidation'   => true,
        'validateOnSubmit'       => true,
        'validateOnChange'       => true,
        'validateOnType'         => true,
    ])
    ?>
    <?= $activeForm->field($membersBans, 'username', [
        'template' => '{label}{input}{hint}{error}'
    ])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете потребителско име']);
    ?>
    <?= $activeForm->field($membersBans, 'end_date', [
        'template' => '{label}{input}{hint}{error}'
    ])->textInput(['class' => 'form-control datepicker', 'placeholder' => 'Въведете период на бана']);
    ?>
    <?= $activeForm->field($membersBans, 'reason', [
        'template' => '{label}{input}{hint}{error}'
    ])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете причина за бана']);
    ?>
    <div class="form-group">
        <?= Html::submitButton('Добави', ['type' => 'submit', 'class' => 'btn btn-default']) ?>
    </div>
    <?php ActiveForm::end()?>
</div>


<div class="the-box">
    <?php
    $activeForm = ActiveForm::begin([
        'id'                     => 'banIp',
        'enableClientValidation' => true,
        'enableAjaxValidation'   => true,
        'validateOnSubmit'       => true,
        'validateOnChange'       => true,
        'validateOnType'         => true,
    ])
    ?>
    <?= $activeForm->field($membersBans, 'ban_ip', [
        'template' => '{label}{input}{hint}{error}'
    ])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете IP адрес или цяла мрежа']);
    ?>
    <?= $activeForm->field($membersBans, 'end_date', [
        'template' => '{label}{input}{hint}{error}'
    ])->textInput(['class' => 'form-control datepicker', 'placeholder' => 'Въведете период на бана']);
    ?>
    <?= $activeForm->field($membersBans, 'reason', [
        'template' => '{label}{input}{hint}{error}'
    ])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете причина за бана']);
    ?>
    <div class="form-group">
        <?= Html::submitButton('Добави', ['type' => 'submit', 'class' => 'btn btn-default']) ?>
    </div>
    <?php ActiveForm::end() ?>
</div>

And it doesn't seem to work. Any ideas?

解决方案

Id in ActiveForm does't mean id in $_POST. You should use:

$membersBans->load(Yii::$app->request->post())

or

$membersBans->load(Yii::$app->request->post('MembersBans'))

for load attributes from form.

For example multiple forms from CeBe (http://www.yiiframework.com/forum/index.php/topic/53935-solved-subforms/page__p__248184#entry248184)

public function actionCreate()
{
    $user = new User;
    $profile = new Profile;

    if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && Model::validateMultiple([$user, $profile])) {

        $user->save(false); // skip validation as model is already validated
        $profile->user_id = $user->id; // no need for validation rule on user_id as you set it yourself
        $profile-save(false);

        return $this->redirect(['view', 'id' => $user->id]);
    } else {
        return $this->render('create', [
            'user' => $user,
            'profile' => $profile,
        ]);
    }
}

In your action you use one model. I think you should extends MembersBans to MembersBansIp class. And your action:

public function actionList() {
    $membersBans = new MembersBans();
    $membersBansIp = new MembersBansIp();
    if ($membersBans->load(Yii::$app->request->post())) {
        $membersBans->banMember();
    }
    if ($membersBansIp->load(Yii::$app->request->post())) {
        $membersBansIp->banIp();
    }
    return $this->render('list', [
                'membersBans' => $membersBans,
                'membersBansIp' => $membersBansIp,
    ]);
}

In view:

<?php
    $activeForm = ActiveForm::begin([
            'id' => 'banMember',
])
?>

    <?= $activeForm->field($membersBans, 'fieldMembersBans') ?>
    <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
    <?php ActiveForm::end() ?>
<?php
    $activeForm = ActiveForm::begin([
            'id' => 'banMemberIp',
])
?>

    <?= $activeForm->field($membersBansIp, 'usernameMembersBansIp') ?>
    <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
    <?php ActiveForm::end() ?>

EDIT

I put your code. He is work. https://yadi.sk/i/y7PkwGUPekjPD https://yadi.sk/i/h8dCYQz3ekk2B

But I change controller to this

$membersBans = new MembersBans();
        if ($membersBans->load(Yii::$app->request->post())) {
            $membersBans->banMember();
        }
        if ($membersBans->load(Yii::$app->request->post())) {
            $membersBans->banIp();
        }

And in model change Members to User, because I have not Members objects:

$memberInfo = User::findByUsername($this->username);
        if ($memberInfo) {
            $this->ban_memberid = $memberInfo->id;

Resume: your code is worked. Change controller, how I written up.

这篇关于Yii2 一个动作中的多种形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 06:43