G
G
grippin2015-09-25 15:44:50
Yii
grippin, 2015-09-25 15:44:50

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

actionSubscribe:
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

[[+comments_count]] answer(s)
I
Igor Makarov, 2015-09-25
@onqu

If it's Yii2
1. You are calling validation 2 times each time.

// первый
$model->validate()

// второй
$model->save()

To avoid this, you must either remove the direct call to validate, or pass false to the save call.
if ($model->validate() && $model->save(false)) 
   ...

2. You need to check what the load method returned
if ($model->load($request->post()) && $model->save()) {
    // сохранили и что-то делаем
}

3. $_POST["email"] will never arrive if you do this when displaying the form:
// $model instanceof Subscription
$form->field($model, 'email')->textInput();

then $_POST will arrive:
[
    'Subscription' => [
        'email' => '[email protected]'
    ]
]

4. Validation for unique can be done like this
public function rules()
{
    return [
        ['email', 'unique'],
    ];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question