S
S
Sandro_s2018-10-08 18:26:38
Yii
Sandro_s, 2018-10-08 18:26:38

How to save data from contact form to database?

There is a contactform table in the database with the fields name,email, subject,body,id
Just in the form via $this->save(); saves nothing. Tried to write saveContactform method in controller and call it in view - but maybe there is a bug somewhere.
In addition, the user, in addition to the data, also enters a captcha. In order for the captcha code to be checked, it must be a property of the model class, moreover, a public property, otherwise the code entered will not be correct each time. And it turns out that when the model is saved, the captcha code is also added to the database, but it’s not needed there.
Now, after filling out the form, the letter is sent, but nothing is saved and redirects to 404 pages.
In the debug, routing 'index/contact'
method 'POST'
$_GET
Empty.
$_POST
_csrf - hash
contact form

[
    'name' => 'Fel'
    'email' => '[email protected]'
    'subject' => 'ggg'
    'body' => 'ggj'
    'verifyCode' => 'tkjatuk'
]

contact-button ''
$_FILES
Empty.
$_COOKIE - hash
In logs
yii\web\HttpException:404
spoiler
yii\base\InvalidRouteException: Unable to resolve the request: index/saveContactform in D:\sites\yii2.loc\vendor\yiisoft\yii2\base\Controller.php:128
Stack trace:
#0 D:\sites\yii2.loc\vendor\yiisoft\yii2\base\Module.php(528): yii\base\Controller->runAction('saveContactform', Array)
#1 D:\sites\yii2.loc\models\Contactform.php(108): yii\base\Module->runAction('index/saveConta...')
#2 D:\sites\yii2.loc\controllers\IndexController.php(37): app\models\Contactform->contact('[email protected]')
#3 [internal function]: app\controllers\IndexController->actionContact()
#4 D:\sites\yii2.loc\vendor\yiisoft\yii2\base\InlineAction.php(57): call_user_func_array(Array, Array)
#5 D:\sites\yii2.loc\vendor\yiisoft\yii2\base\Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#6 D:\sites\yii2.loc\vendor\yiisoft\yii2\base\Module.php(528): yii\base\Controller->runAction('contact', Array)
#7 D:\sites\yii2.loc\vendor\yiisoft\yii2\web\Application.php(103): yii\base\Module->runAction('index/contact', Array)
#8 D:\sites\yii2.loc\vendor\yiisoft\yii2\base\Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#9 D:\sites\yii2.loc\web\index.php(12): yii\base\Application->run()
#10 {main}

Next yii\web\NotFoundHttpException: Страница не найдена. in D:\sites\yii2.loc\vendor\yiisoft\yii2\web\Application.php:115
Stack trace:
#0 D:\sites\yii2.loc\vendor\yiisoft\yii2\base\Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#1 D:\sites\yii2.loc\web\index.php(12): yii\base\Application->run()
#2 {main}

contact form (model)
spoiler
<?php

namespace app\models;

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

 /**
 * This is the model class for table "contactform".
 *
 * @property string $id
 * @property string $name
 * @property string $email
 * @property integer $subject
 * @property double $body
 * @property string $verifyCode
 
 */

class Contactform extends ActiveRecord
{
    public $name;
    public $email;
    public $subject;
    public $body;
    public $verifyCode;


     public static function tableName()
    {
        return 'contactform';
    }
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
       
           /* Поля обязательные для заполнения */
            [ ['name', 'email', 'subject', 'body'], 'required'],
            /* Поле электронной почты */
            ['email', 'email'],
            /* Капча */
            ['verifyCode', 'captcha', 'captchaAction'=>'index/captcha'],
          /*  ['verifyCode', 'captcha','captchaAction'=>'/contactus/default/captcha'],*/

        ];

    }

    /**
     * @return array customized attribute labels
     */
    public function attributeLabels()
    {
        return [
            'verifyCode' => 'Подтвердите код',
            'name' => 'Имя',
            'email' => 'Электронный адрес',
            'subject' => 'Тема',
            'body' => 'Сообщение',
        ];
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     * @param  string  $email the target email address
     * @return boolean whether the model passes validation
     */
   
    
    public function contact($emailto)
    {
        if ($this->validate()) {

        Yii::$app->mailer->compose()
            ->setFrom(Yii::$app->params['adminEmail']) /* от кого */
            ->setTo([$this->email => $this->name,'[email protected]' => 'yii2.loc']) 
            ->setSubject('Админ') /* имя отправителя */
            ->setTextBody('Добрый день! Ваше сообщение принято!')->setCharset('UTF-8') /* текст сообщения */

               ->send(); /* функция отправки письма */
            /*Cохранить данные */
            Yii::$app->runAction('index/saveContactform');
         $this->saveContactForm()
save();
            return true;
        } else {
            return false;
        }
    }

}

IndexController
spoiler
<?php


namespace app\controllers;

use Yii;
use yii\App\Controller;
use app\models\ContactForm;
use yii\web\Request;



class IndexController extends AppController
{


  public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ]
        ];
    }

    public function actionContact()
    {
        
       // $this->layout = 'contact';
        $this->layout = false;
        

          /* Создаем экземпляр класса */
        $model = new ContactForm();
        /* получаем данные из формы и запускаем функцию отправки contact, если все хорошо, выводим сообщение об удачной отправке сообщения на почту */
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');
            return $this->refresh();
        /* иначе выводим форму обратной связи */
        } else {
           return $this->render('contact', [
               'model' => $model,
         ]);
           /*  return $this->render('contact', compact('contact'));*/
        }
    }

     protected function saveContactform(){


            //создаем объект модели
            $contactform = new contactform();
            
            $contactform->name =$id['name'];
            $customer->email = $id['email'];
            $customer->subject = $id['subject'];
            $customer->body =$id ['body'];
            $customer->save();
        }
}

contact (view)
spoiler
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;



/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model app\models\ContactForm */

$this->title = 'Контакты';
?>
<article class="col-xs-12 col-lg-6">

    <div class="row margin-null">
        <!-- Заголовок -->
        <h1><?= Html::encode($this->title) ?></h1>
    
        <!-- Условие отправления формы, если она отправлена выводим сообщение -->
        <?php if (Yii::$app->session->hasFlash('contactFormSubmitted')): ?>
    
        <div class="alert alert-success">
            Спасибо за обращение к нам. Мы постараемся ответить вам как можно скорее.
        </div>
    
        <!-- иначе выводим форму -->
        <?php else: ?>
    
           <?php $form = ActiveForm::begin([
                'id' => 'contact-form', /* Идентификатор формы */
                'options' => ['class' => 'form-horizontal'], /* класс формы */
                'fieldConfig' => [ /* классы полей формы */
                    'template' => "<div class=\"col-lg-3\">{label}</div>\n<div class=\"col-lg-9\">{input}</div>\n<div class=\"col-lg-12 col-lg-offset-3 \">{error}</div>"
               
                ],
            ]); ?>
            <!-- Поля формы и капча -->
            <?= $form->field($model, 'name') ?>
            <?= $form->field($model, 'email') ?>
            <?= $form->field($model, 'subject') ?>
       
            <?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
            <?=$form->field($model, 'verifyCode')->widget(Captcha::className(), [
                'captchaAction' => '/index/captcha',
                'template' => '<div class="row"><div class="col-lg-4">{image}</div><div class="col-lg-7">{input}</div></div>',
            ])?>
            <!-- Кнопка отправки формы-->
            <div class="form-group">
                <?= Html::submitButton('Отправить сообщение', ['class' => 'btn btn-default waves-effect btn-color-orange btn-color-orange-long', 'name' => 'contact-button']) ?>
            </div>
            
            <?php ActiveForm::end(); ?>
    
        <?php endif; ?>
    
    </div>
</article>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-10-08
@Sandro_s

Good evening.
In the model you create a model object new ContactForm() , and in the saveContactForm() method you try to create an object from this model new contactform() .
This is the first.
Second, what error do you see when saving to the database?
Remove the saveContactForm() method and bring the contact() method and action in the controller to look like this.
ContactForm::contact() method

public function contact() // где Вы в методе используете $emailto? Нигде! Удалить
    {
        if ($this->validate()) {

            Yii::$app->mailer->compose()
                ->setFrom(Yii::$app->params['adminEmail']) /* от кого */
                ->setTo([$this->email => $this->name,'[email protected]' => 'yii2.loc'])
                ->setSubject('Админ') /* имя отправителя */
                ->setTextBody('Добрый день! Ваше сообщение принято!')->setCharset('UTF-8') /* текст сообщения */
                ->send(); /* функция отправки письма */
            return true;
        } else {
            return false;
        }
    }

Action IndexController::actionContact()
public function actionContact()
    {
        $this->layout = false;

        /* Создаем экземпляр класса */
        $model = new ContactForm();
// удаляем Yii::$app->params['adminEmail'], так как в методе используете напрямую
// ->setFrom(Yii::$app->params['adminEmail'])
        if ($model->load(Yii::$app->request->post()) && $model->contact()) {
            // $model->save(false) отменяем валидацию, так как уже прошли в методе $model->contact()
            if($model->save(false)){
                Yii::$app->session->setFlash('contactFormSubmitted');
                return $this->refresh();
            }
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
            /*  return $this->render('contact', compact('contact'));*/
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question