Answer the question
In order to leave comments, you need to log in
Why doesn't the duplicate check work?
Wrote the Subscribe function. But for some reason the check doesn't work.
My Subscription Class:
public static function tableName()
{
return 'Subscription';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['email'], 'required'],
[['email'], 'email'],
[['email'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'email' => 'Email',
];
}
public function actionSubscribe() {
$model = new Subscription();
if (Yii::$app->request->isAjax) {
$model->load(Yii::$app->request->post());
return ($model->validate() && $model->save()) ?
Yii::t("contact", "Thank you. You'll get latest news") :
Yii::t("common", "Error");
}
if (isset($_POST["email"])) {
$result = null;
$duplicate = Subscription::findOne(["email" => $_POST["email"]]);
if ($duplicate)
$result = ['status' => 0, "message" => Yii::t("common", "This email already subscribed to our news")];
else {
$model->email = $_POST["email"];
if ($model->validate() && $model->save()) {
$result = ['status' => 1, "message" => Yii::t("common", "Successfully subscribed to our news")];
}
}
return $result;
}
}
Answer the question
In order to leave comments, you need to log in
If it's Yii2
1. You are calling validation 2 times each time.
// первый
$model->validate()
// второй
$model->save()
if ($model->validate() && $model->save(false))
...
if ($model->load($request->post()) && $model->save()) {
// сохранили и что-то делаем
}
// $model instanceof Subscription
$form->field($model, 'email')->textInput();
[
'Subscription' => [
'email' => '[email protected]'
]
]
public function rules()
{
return [
['email', 'unique'],
];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question