I
I
Igor Vasiliev2017-07-11 01:20:21
Yii
Igor Vasiliev, 2017-07-11 01:20:21

How to send Post requests via beginForm in Yii2?

Hello.
---
Material:
=

// вьюха
...
                        <?= Html::beginForm(['/phone'], 'post', ['name' => 'send']) ?>
                            <div class="input-group">
                                <?=Html::input('text', 'action', $telefon,['type' => 'hidden']) ?>
                                <?=Html::input('text', 'code', '',['class' => 'form-control input-lg', 'placeholder' => 'введите код из SMS']) ?>
                                <span class="input-group-btn">
                                    <?= Html::submitButton('Активировать', ['class' => 'btn btn-danger btn-lg btn-flat']) ?>
                                </span>
                            </div>
                        <?= Html::endForm() ?>
...

and
// controller
...
    public function actionPhone() {
        $model = User::findOne(Yii::$app->user->identity->id); // записываем номер телефона в БД
        if ($model->load(Yii::$app->request->post()) && $model->save()) { // обновляем запись
            Yii::$app->session->setFlash('contactPhone'); // выводим информацию об успехе
            if(!$model->save()){
                throw new \yii\web\HttpException(500, 'Невозможно сохранить'); // или показываем ошибку в записи
            }
            return $this->refresh(); // обновляем страницу
        }
        if(Yii::$app->request->post('send')){ // если отправилась форма с name "send"
            if(Yii::$app->request->post('code') == Yii::$app->request->post('action')){ // и эти переданные post данные одинаковые
                return $this->redirect(['/account/user', 'id' => Yii::$app->user->identity->id]); // тогда перенаправляем на страницу
            } else {
                Yii::$app->getSession()->setFlash('error', 'Вы ввели не верный код активации!'); // или посылаем ошибку
            }
        }
        return $this->render('phone', ['model' => $model]); // выводим результат
    }
...

Explanations: The controller first updates the field in the DB row, if it is empty, it adds the phone number. Then, when the script wrote down the phone number, another form appears with random numbers and an empty field where you need to enter numbers from sms - when the post data starts to be sent and validated, then I will transfer the hidden data to the controller. As you understand, the second form does not send anything to the database, but only checks whether the data is the same or different, if it matches, the sms script will fix this number as confirmed.
QUESTION: How to correctly transfer post data so that the controller can see and process them, everywhere there is only material on processing data in the database, but I did not find anything on processing post data. Please tell me how to implement it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-07-11
@Isolution666

How to send post data correctly

send a post request, form or otherwise. You have a form, it sends a post request, so you have already implemented it, what's the problem?
$_POST //тут пост запрос, как обычно в php
Yii::$app->request->post() //тоже самое, но средствами yii

What do you understand by "processed", here is an abstract example:
if(Yii::$app->request->isPost){
   $post = Yii::$app->request->post();
   echo $post['some_data'];
}else{
   echo 'не пришел post запрос, плачем всем отделом';
}

D
Dmitry, 2017-07-11
@slo_nik

Good morning.
Why don't you use ActiveForm?
Is it? Here you get user data by his id.
PS
Why send anything at all? Maybe you need to compare the data through the validator, if they match, write to the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question