Модель:
Код: Выделить всё
<?php
namespace app\models;
use yii\base\Model;
class TestForm extends Model{
public $name;
public $email;
public $text;
public function attributeLabels(){
return[
'name'=>'Имя',
'email'=>'E-mail',
'text'=>'Текст сообщения',
];
}
public function rules(){
return [
[ ['name', 'email'], 'required' ],
[ 'email', 'email' ],
[ 'name', 'string', 'length' => [2,5] ],
[ 'name', 'myRule' ],
[ 'text', 'trim' ],
];
}
public function myRule($attr){
if( !in_array($this->$attr, ['hello', 'world']) ){
$this->addError($attr, 'Wrong!');
}
}
}
Код: Выделить всё
public function beforeAction($action){
if($action->id=='page'){
$this->enableCsrfValidation=false;
}
return parent::beforeAction($action);
}
public function actionPage(){
$form_model = new TestForm();
$array_if= " ";
if(\Yii::$app->request->isAjax){
debug($_POST);
Yii::$app->request->post();
return 'Запрос принят!';
}
if ($form_model->load(Yii::$app->request->post())) {
// Работаем с принятыми да
нными
$array_if = $form_model->TestForm->text;
debug($form_model);
}
debug($form_model);
return $this->render('page', compact('array_if','form_model'));
}
Код: Выделить всё
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<?php $form = ActiveForm::begin() ?>
<?= $form->field($form_model, 'text') ?>
<?= Html::submitButton('Отправить', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
<?php
$js = <<<JS
$('form').on('beforeSubmit', function(){
var data = $(this).serialize();
$.ajax({
url: 'index.php?r=site/page',
type: 'POST',
data: data,
success: function(res){
console.log(res);
console.log(data);
},
error: function(){
alert('Error!');
}
});
return false;
});
JS;
$this->registerJs($js);
?>
дебаг
<?php
debug($array_if);//здесь не выводится
?>
<?php
debug($form_model);//здесь пусто
?>
form_model
Код: Выделить всё
<pre>Array
(
[_csrf] => 4AITkDB-hoBWicn-xa-2FrpH5ZregtvjXgz9kvhuFh2pWyvDADjO5QHcvbqh-ock6wavyJX0ns4xZZLYnwRyaQ==
[TestForm] => Array
(
[text] => Пров
)
)
</pre>Запрос принят! index.php:994:1
_csrf=4AITkDB-hoBWicn-xa-2FrpH5ZregtvjXgz9kvhuFh2pWyvDADjO5QHcvbqh-ock6wavyJX0ns4xZZLYnwRyaQ%3D%3D&TestForm%5Btext%5D=%D0%9F%D1%80%D0%BE%D0%B2