使用yii2中的模型重定向到“从哪个表单数据提交”的先前地址

时间:2018-02-12 15:34:59

标签: yii2 yii2-advanced-app yii2-model yii2-validation

我创建了一个小部件,用于在 layouts/main.php 页脚部分中呈现表单。

这是一个名为 common\widget\SubscriberFormWidget.php

的小部件文件
<?php
namespace common\widgets;

use Yii;
use yii\base\Widget;
use common\models\Subscriber;

class SubscriberFormWidget extends Widget
{

    /**
      *@return string
      */

    public function run()
    {
        $model = new Subscriber();
         return $this->render('_form', [
            'model' => $model
        ]);
    }
}

这是 _form

中上面小部件中使用的 common\widget\views\_form.php 文件
<?php

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

/* @var $this yii\web\View */
/* @var $model common\models\Subscriber */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(['action' => ['subscriber/subscribe']]); ?>
    <div class="row">
        <div class="col-md-6">
            <?= $form->field($model, 'email')->textInput(['maxlength' => true, 'placeholder' => 'Enter @ Email to subscribe!'])->label(false) ?>
        </div>
        <div class="col-md-6">
            <?= Html::submitButton('Subscribe', ['class' => 'btn btn-success']) ?>
        </div>
    </div>

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

这是控制器文件 frontend\controllers\SubscriberController.php

<?php

namespace frontend\controllers;

use Yii;
use common\models\Subscriber;
use common\models\SubscriberSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * SubscriberController implements the CRUD actions for Subscriber model.
 */
class SubscriberController extends Controller
{


    /**
     * Creates a new Subscriber model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionSubscribe()
    {
        $model = new Subscriber();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'You have successfully subscribed My-Blog. You will get notification whenever New post is published');

                return $this->redirect(Yii::$app->request->referrer);
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to subscribe for the provided email address.');
            }
        }

        return $this->redirect([Yii::$app->request->referrer, ['model' => $model]]);
    }

    /**
     * Creates a new Subscriber model.
     * If unsubscribe is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
}

我在页脚部分 layouts\main.php 中使用了小部件

<footer class="footer">
    <div class="container">
        <div class="row">
            <div class="col-md-3">
                <p class="pull-left">&copy; <?= Html::encode(Yii::$app->name) ?> <?= date('Y') ?></p>
            </div>
            <div class="col-md-6 text-justify" style="border-left : 2px solid black; border-right: 2px solid black">
                <?= SubscriberFormWidget::widget(); ?>
                <p>
                    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into elec
                </p>
            </div>
            <div class="col-md-3">
                 <p class="pull-right"><?= Yii::powered() ?></p>
            </div>
        </div>
    </div>
</footer>

这是用于控制器 common\models\Subscriber.php

的模型
   <?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;

/**
 * This is the model class for table "subscriber".
 *
 * @property int $id
 * @property string $email
 * @property string $token
 * @property int $status
 * @property int $created_at
 * @property int $updated_at
 */
class Subscriber extends \yii\db\ActiveRecord
{
    const STATUS_DEACTIVE = 0;
    const STATUS_ACTIVE = 1;

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

    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
                'value' => new Expression('NOW()'),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['email'], 'required'],
            [['status', 'created_at', 'updated_at'], 'safe'],
            [['email'], 'string', 'max' => 60],
            [['token'], 'string', 'max' => 255],
            [['token'], 'unique'],
            [['email'], 'unique',  'targetClass' => '\common\models\Subscriber', 'message' => 'This email has already subscribed our blog.','filter' => ['!=','status' ,0]],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'email' => 'Email',
            'token' => 'Token',
            'status' => 'Status',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    /**
     * Generates subscriber token
     */
    public function generateSubscriberToken()
    {
       return $this->token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Send Email when successfully subscribe
     */

     public function sendEmail()
    {
        $subscribers = self::find()->where(['email' => $this->email])->one();

        //set flag for sending email
        $sendMail = false;
        //email subject
        $subject = '';

        //generate token
        $token = $this->generateSubscriberToken();

        //if email found in subscribers
        if ($subscribers !== null) {

            //check if inactive
            if ($subscribers->status !== self::STATUS_ACTIVE) {

                //assign token
                $subscribers->token = $token;

                //set status to active
                $subscribers->status = self::STATUS_ACTIVE;

                print_r($subscribers->errors);
                //update the recrod
                if (!$subscribers->save()) {
                    return false;
                }

                //set subject
                $subject = 'Welcome back ' . $this->email . 'Thank you for subscribing ' . Yii::$app->name . '<br /><br /> You will receive notification whenever new trick or post is published to website';
                $sendMail = true;
            }
        } else { //if email does not exist only then insert a new record
            $this->status = 1;
            if (!$this->save()) {

                return false;
            }
            $subject = 'Thank you ' . $this->email . ' for subscribing ' . Yii::$app->name . '<br /><br /> You will receive notification whenever new trick or post is published to website';
            $sendMail = true;
        }

        //check if send mail flag set
        if ($sendMail) {
            return Yii::$app->mailer
                ->compose()
                ->setFrom(['noreply@my-blog.com' => Yii::$app->name . ' robot'])
                ->setTo('piyush@localhost')
                ->setSubject('Subscription : ' . Yii::$app->name)
                ->setHtmlBody($subject)
                ->send();
        }

    }
}

现在我希望表单能够进行验证。如果用户输入了已经注册的任何错误输入,那么此消息应该返回到提交表单数据的视图文件。

2 个答案:

答案 0 :(得分:1)

Controlelr::redirect()接受url和可选的status code参数 您未在所提供的代码段中正确调用它。
我相信您只是尝试使用url参数(单个数组参数)并跳过状态代码。

您也不能依赖引荐来指回上一页。您需要在表单页面中保存要返回的路径

Url::remember([Yii::$app->requestedRoute]));

以后再使用它返回表单

return $this->redirect([Url::previous(), ['model' => $model]]);

答案 1 :(得分:0)

您可以设置Yii::$app->user->returnUrl,然后使用$this->goBack()导航回上一页。

一种好方法是在控制器 beforeAction 中添加SubscribeController功能,如下所示。

public function beforeAction($action)
{
    if (parent::beforeAction($action)) {
        if($action->id=='subscribe'){
            Yii::$app->user->returnUrl = Yii::$app->request->referrer;
        }
    }
    return true;
} 

并替换

return $this->redirect([Yii::$app->request->referrer, ['model' => $model]]);

以下

return $this->goBack();

现在,无论您提交页脚表单的哪个页面,它都会导航回该页面。

我注意到您没有检查表单中的sessionFlash error变量的另一件事,您需要收到错误消息,如

if(Yii::$app->session->hasFlash('error')){

   echo '<div class="alert alert-danger">
          <strong>Danger!</strong>'. Yii::$app->session->getFlash('error').'
       </div>';
}

我可以在previous answer中提供更好的方式来显示sessionFlash消息,以避免手动添加代码,只会在设置后自动显示会话消息。

希望它可以帮助你