Заказ окна с сайта - uniqcle/Yii2 GitHub Wiki

Делаем миграцию php yii migrate/create create_window_order_table

use yii\db\Migration;

/**
 * Handles the creation of table `{{%window_order}}`.
 */
class m190725_084430_create_window_order_table extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->createTable('{{%window_order}}', [
            'id' => $this->primaryKey(),
            'width' => $this->integer(255), 
            'height' => $this->integer(255), 
            'camera' => $this->integer(5), 
            'stvorki' => $this->integer(5), 
            'povorot' => $this->integer(5), 
            'color' => $this->string(256), 
            'podokonnik' => $this->boolean(), 
            'email' => $this->string(256), 
            'name' => $this->string(256)

        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropTable('{{%window_order}}');
    }
}

В контроллере frontend/controllers/WindowController.php

namespace frontend\controllers; 

use Yii; 
use yii\web\Controller; 
use frontend\models\Window; 
use console\models\Sending; 

class WindowController extends Controller 
{


	public function actionOrder(){

		//$arResult = []; 
		 
		$model = new Window(); 

		$formData = Yii::$app->request->post(); 

		if( Yii::$app->request->isPost ){
			
			$model->attributes = $formData; 

			if( $model->validate() && $model->save() ){


				$orderAttributes = $model->attributes; 

				$sendingToAdmin = Sending::toadmin( $orderAttributes ); 


				if( $sendingToAdmin ){
					
					Yii::$app->session->setFlash('success', 'Ваша заявка принята');

				} 

			}
		}
		return $this->render('order', [
			 'model' => $model
		]); 
	}
}

В модели frontend/models/Window.php

namespace frontend\models; 

use Yii; 
use yii\base\Model; 

class Window extends Model 
{	
	public $width; 
	public $height; 
	public $camera; 
	public $stvorki; 
	public $povorot; 
	public $color; 
	public $podokonnik; 
	public $email; 
	public $name; 

	public function rules(){
		return [
			[['email', 'name'], 'required'], 
			[['width', 'height', 'camera', 'stvorki', 'povorot', 'color', 'podokonnik'], 'safe']
		]; 
	}

	public function save(){

		$sql = "INSERT INTO window_order (id, width, height, camera, stvorki, povorot, color, podokonnik, email, name) VALUES (null, '{$this->width}', '{$this->height}', '{$this->camera}', '{$this->stvorki}', '{$this->povorot}', '{$this->color}', '{$this->podokonnik}', '{$this->email}', '{$this->name}'); "; 

		return Yii::$app->db->createCommand( $sql )->execute();
	}


}

Во вью frontend/views/window/order.php

<h3>Заказ окна</h3>

<form method = "POST">
  <div class="form-group row">
    <label for="width" class="col-sm-2 col-form-label">Ширина окна*</label>
    <div class="col-sm-10">
      <input type="number" name = "width" class="form-control" id="width" min="70" max="210" placeholder="от 70 до 210 см">
    </div>
  </div>

    <div class="form-group row">
    <label for="height" class="col-sm-2 col-form-label">Высота окна*</label>
    <div class="col-sm-10">
      <input type="number" name = "height" class="form-control" id="height" min="100" max="200" placeholder="от 100 до 200 см">
    </div>
  </div>

   <div class="form-group row">
	   	 <label for="camera" class="col-sm-2 col-form-label">Количество камер*</label>
	   	<div class="col-sm-10">
			<div class="form-check ">
				<input class="form-check-input" type="radio" name="camera" id="inlineRadio1" value="1">
				<label class="form-check-label" for="inlineRadio1">1</label>

				<input class="form-check-input" type="radio" name="camera" id="inlineRadio2" value="2">
				<label class="form-check-label" for="inlineRadio2">2</label>

				<input class="form-check-input" type="radio" name="camera" id="inlineRadio3" value="3">
				<label class="form-check-label" for="inlineRadio3">3</label>
			</div>
		 
	   </div>
	</div>

	<div class="form-group row">
    <label for="stvorki" class="col-sm-2 col-form-label">Общее кол-во створок*</label>
     <div class="col-sm-10">
    	<input type="number" name = "stvorki" class="form-control" id="stvorki" min="1" max="5" placeholder="от 1 до 5">
	</div>
  </div>

  	<div class="form-group row">
    <label for="povorot" class="col-sm-2 col-form-label">Количество поворотных створок*</label>
     <div class="col-sm-10">
    	<input type="number" name = "povorot" class="form-control" id="povorot" min="1" max="5" placeholder="от 1 до 5">
	</div>
  </div>

    <div class="form-group row">
    <label for="color" class="col-sm-2 col-form-label">Цвет*</label>
     <div class="col-sm-10">
	    <select class="form-control" name = "color" id="color">
	      <option> Выбрать цвет </option>
	      <option value = "Голубой" style="background-color: blue">Голубой</option>
	      <option value = "Зеленый" style="background-color: green">Зеленый</option>
	      <option value = "Оранжевый" style="background-color: orange">Оранжевый</option>
	      <option value = "Черный" style="background-color: black">Черный</option>
	      <option value = "Красный" style="background-color: red">Красный</option>
	    </select>
 
	</div>
  </div>


    <div class="form-group row">
    <label for="podokonnik" class="col-sm-2 col-form-label">Наличие подоконника*</label>
     <div class="col-sm-10">
    	 <input class="form-check-input" type="radio" name="podokonnik" id="podokonnik" value="1"> да 
    	  <input class="form-check-input" type="radio" name="podokonnik" id="podokonnik" value="0"> нет
	</div>
  </div>

  
  <div class="form-group row">
    <label for="email" class="col-sm-2 col-form-label">Вам email*</label>
    <div class="col-sm-10">
      <input type="text" name = "email" class="form-control" id="email" placeholder="[email protected]">
    </div>
  </div>

    <div class="form-group row">
    <label for="name" class="col-sm-2 col-form-label">Имя*</label>
    <div class="col-sm-10">
      <input type="text" name = "name" class="form-control" id="name" placeholder="Иван">
    </div>
  </div>


  <div class="form-group row">
    <div class="col-sm-10">
      <button type="submit" class="btn btn-primary">Заказать окно</button>
    </div>
  </div>
 </form>

Класс Отправка console/models/Sending.php

namespace console\models; 

use Yii; 
use yii\helpers\Console; 

class Sending
{

	public static function run( $emailList, $today ){

		$arResult = []; 

		foreach($emailList as $subscriber):

		    $result = Yii::$app->mailer->compose("/mail/report.php", [ //шаблон contact в common/mail
						'subscriber' => $subscriber['fio'], 
						'salary' => $subscriber['salary'], 
						'today' => $today
						]) 
		            ->setFrom( ['[email protected]' => 'Андрей'] ) 
		            ->setTo( $subscriber['email'] ) // кому отправляем  
		            ->setSubject( 'Зарплатная ведомость '.$subscriber['fio'] ) // тема письма
	/*	            ->setTextBody('Текст...') //  Закомментировать, если передаем в View
		            ->setHtmlBody('Текст...')*/
		            ->send();

		    $fio = $subscriber['fio']; 
		    $salary = $subscriber['salary']; 

		    $arResult[$fio]['fio'] = $fio; 
		    $arResult[$fio]['salary'] = $subscriber['salary']; 
		    $arResult[$fio]['date'] = $today; 


	    endforeach; 

    return $arResult; 
	}


	public static function toadmin( $orderAttributes ){



		$result = Yii::$app->mailer->compose("order.php", [ //шаблон contact в common/mail
						'orderAttributes' => $orderAttributes, 
						]) 
		            ->setFrom( ['[email protected]' => 'Андрей'] ) 
		            ->setTo( '[email protected]' ) // кому отправляем  
		            ->setSubject( 'Заказ с сайта ' ) // тема письма
	/*	            ->setTextBody('Текст...') //  Закомментировать, если передаем в View
		            ->setHtmlBody('Текст...')*/
		            ->send();

		return $result; 
	}
}

Правки в frontend/config/main.php

...
 'mailer' => [
                    'class' => 'yii\swiftmailer\Mailer',
                    'viewPath' => '@common/mail',
                    'transport' => [
                        'class' => 'Swift_SmtpTransport',
                        'host' => 'smtp.yandex.ru',
                        'username' => 'u***@yandex.ru', //
                        'password' => '*****',
                        'port' => '465',
                        'encryption' => 'ssl', // у яндекса SSL
                    ],
         
                    'useFileTransport' => false, // будем отправлять реальные сообщения, а не в файл
                ],
...

Вид письма common/mail/order.php

<h3>Клиент <?=$orderAttributes['name']; ?> с сайта</h3>
Email: <?=$orderAttributes['email']; ?>

<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">Поле</th>
      <th scope="col">Значение</th>
 
    </tr>
  </thead>
  <tbody>
 
    <tr>
      <th scope="row">Ширина</th>
      <td><?=$orderAttributes['width']; ?></td>
     </tr>

     <tr>
      <th scope="row">Высота</th>
      <td><?=$orderAttributes['height']; ?></td>
     </tr>

      <tr>
      <th scope="row">количество камер </th>
      <td><?=$orderAttributes['camera']; ?></td>
     </tr>

     <tr>
      <th scope="row">общее количество створок</th>
      <td><?=$orderAttributes['stvorki']; ?></td>
     </tr>

     <tr>
      <th scope="row">количество поворотных створок </th>
      <td><?=$orderAttributes['povorot']; ?></td>
     </tr>

     <tr>
      <th scope="row">цвет</th>
      <td><?=$orderAttributes['color']; ?></td>
     </tr>

      <tr>
      <th scope="row">наличие подоконника </th>
      <td><?=$orderAttributes['podokonnik']; ?></td>
     </tr>
 
 
  </tbody>
</table>
⚠️ **GitHub.com Fallback** ⚠️