重定向到以前的地址;从中提交表格数据;模型为yii2
我已经创建了一个小部件,用于在重定向到以前的地址;从中提交表格数据;模型为yii2,yii2,yii2-advanced-app,yii2-model,yii2-validation,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 { /** *@r
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
]);
}
}
<?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(); ?>
<?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
*/
}
<?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();
}
}
}
这是控制器文件frontend\controllers\SubscriberController.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
]);
}
}
<?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(); ?>
<?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
*/
}
<?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();
}
}
}
此模型用于控制器common\models\Subscriber.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
]);
}
}
<?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(); ?>
<?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
*/
}
<?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();
}
}
}
接受url
和可选的状态代码
参数。
您在摆姿势的片段中没有正确调用它。
我相信您试图只使用url参数(单个数组参数)并跳过状态代码
你们也不能依靠推荐人把你们引向上一页。您需要在表单页面中保存要返回的路线
Url::remember([Yii::$app->requestedRoute]);
然后使用它返回表单
return $this->redirect([Url::previous(), ['model' => $model]]);
接受url
和可选的状态代码
参数。
您在摆姿势的片段中没有正确调用它。
我相信您试图只使用url参数(单个数组参数)并跳过状态代码
你们也不能依靠推荐人把你们引向上一页。您需要在表单页面中保存要返回的路线
Url::remember([Yii::$app->requestedRoute]);
然后使用它返回表单
return $this->redirect([Url::previous(), ['model' => $model]]);
您可以设置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>';
}
if(Yii::$app->session->hasFlash('error')){
回声'
危险!”。Yii::$app->session->getFlash('error')。'
';
}
my中提供了一种更好的方式来显示sessionFlash
消息,您可以按照这种方式操作,以避免在任何地方手动添加代码,一旦设置,它将自动向您显示会话mssages
希望它能帮助您您可以设置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>';
}
if(Yii::$app->session->hasFlash('error')){
回声'
危险!”。Yii::$app->session->getFlash('error')。'
';
}
my中提供了一种更好的方式来显示sessionFlash
消息,您可以按照这种方式操作,以避免在任何地方手动添加代码,一旦设置,它将自动向您显示会话mssages
希望它能帮助您是的,这是因为推荐人包含完整的url而不是路线,也许使用\yii\helpers\url::memory()
和\yii\helpers\url::previous()更安全
@PiyushGupta我已经更新了答案。我认为这个方法更好一些,因为Yii::$app->request->referer
几乎可以是任何东西(空域或外部域或任何用户提交的数据)。我还用代码详细更新了问题。希望你们能理解这个问题……@csminbit仍然可以工作。在呈现之前添加Url::记住SubscriberFormWidget.php中的,并使用$this->重定向([Url::previous(),['model'=>$model]])代码>在actionSubscribe()中,它将我重定向到“”而不是“”@是的,这是因为推荐人包含完整的url而不是路线,也许使用\yii\helpers\url::memory()
和\yii\helpers\url::previous()
@piyusgupta我已经更新了答案。我认为这种方法更好一些,因为yii:$app->request->referer
几乎可以是任何东西(null或外部域或任何用户提交的数据)我还用代码详细更新了问题。希望您能理解问题…@csminbit应该仍然有效。在渲染之前,在SubscriberFormWidget.php
中添加Url::记住,并使用$this->重定向([Url::previous(),['model'=>$model]]))
在actionSubscribe()中,它将我重定向到“”而不是“”@csminb@muhammad这不起作用…请检查问题是您正在使用$model->validate()进行验证
但是在规则中,您没有使用任何验证,比如电子邮件是否已经存在,而是使用sendMail
功能验证用户是否已经存在并且处于活动状态,然后添加到会话flash
消息中,它将在flash中显示错误仅当页面在添加消息或重定向后刷新时才显示消息您是否使用页面重新加载提交表单?我使用了模型公共函数规则(){return[[['email'],'required'],[[['status','created_at','updated_at'],'safe'],[[['email'],'string','max'=>60],[['token'],'string','max'=>255],['token'],'unique'],[[['email'],'unique','targetClass'=>